本文整理汇总了C#中System.Threading.Tasks.Task.ContinueWith方法的典型用法代码示例。如果您正苦于以下问题:C# Task.ContinueWith方法的具体用法?C# Task.ContinueWith怎么用?C# Task.ContinueWith使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.ContinueWith方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var firstTask = Task.Factory.StartNew( () => {
Random rnd = new Random();
DateTime[] dates = new DateTime[100];
Byte[] buffer = new Byte[8];
int ctr = dates.GetLowerBound(0);
while (ctr <= dates.GetUpperBound(0)) {
rnd.NextBytes(buffer);
long ticks = BitConverter.ToInt64(buffer, 0);
if (ticks <= DateTime.MinValue.Ticks | ticks >= DateTime.MaxValue.Ticks)
continue;
dates[ctr] = new DateTime(ticks);
ctr++;
}
return dates;
} );
Task continuationTask = firstTask.ContinueWith( (antecedent) => {
DateTime[] dates = antecedent.Result;
DateTime earliest = dates[0];
DateTime latest = earliest;
for (int ctr = dates.GetLowerBound(0) + 1; ctr <= dates.GetUpperBound(0); ctr++) {
if (dates[ctr] < earliest) earliest = dates[ctr];
if (dates[ctr] > latest) latest = dates[ctr];
}
Console.WriteLine("Earliest date: {0}", earliest);
Console.WriteLine("Latest date: {0}", latest);
} );
// Since a console application otherwise terminates, wait for the continuation to complete.
continuationTask.Wait();
}
}
输出:
Earliest date: 2/11/0110 12:03:41 PM Latest date: 7/29/9989 2:14:49 PM
示例2: Main
//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;
class ContinuationOptionsDemo
{
// Demonstrated features:
// TaskContinuationOptions
// Task.ContinueWith()
// Task.Factory
// Task.Wait()
// Expected results:
// This sample demonstrates branched continuation sequences - Task+Commit or Task+Rollback.
// Notice that no if statements are used.
// The first sequence is successful - tran1 and commitTran1 are executed. rollbackTran1 is canceled.
// The second sequence is unsuccessful - tran2 and rollbackTran2 are executed. tran2 is faulted, and commitTran2 is canceled.
// Documentation:
// http://msdn.microsoft.com/library/system.threading.tasks.taskcontinuationoptions(VS.100).aspx
static void Main()
{
Action success = () => Console.WriteLine("Task={0}, Thread={1}: Begin successful transaction",
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
Action failure = () =>
{
Console.WriteLine("Task={0}, Thread={1}: Begin transaction and encounter an error",
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
throw new InvalidOperationException("SIMULATED EXCEPTION");
};
Action<Task> commit = (antecendent) => Console.WriteLine("Task={0}, Thread={1}: Commit transaction",
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
Action<Task> rollback = (antecendent) =>
{
// "Observe" your antecedent's exception so as to avoid an exception
// being thrown on the finalizer thread
var unused = antecendent.Exception;
Console.WriteLine("Task={0}, Thread={1}: Rollback transaction",
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
};
// Successful transaction - Begin + Commit
Console.WriteLine("Demonstrating a successful transaction");
// Initial task
// Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
Task tran1 = Task.Factory.StartNew(success);
// The following task gets scheduled only if tran1 completes successfully
var commitTran1 = tran1.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion);
// The following task gets scheduled only if tran1 DOES NOT complete successfully
var rollbackTran1 = tran1.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion);
// For demo purposes, wait for the sample to complete
commitTran1.Wait();
// -----------------------------------------------------------------------------------
// Failed transaction - Begin + exception + Rollback
Console.WriteLine("\nDemonstrating a failed transaction");
// Initial task
// Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
Task tran2 = Task.Factory.StartNew(failure);
// The following task gets scheduled only if tran2 completes successfully
var commitTran2 = tran2.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion);
// The following task gets scheduled only if tran2 DOES NOT complete successfully
var rollbackTran2 = tran2.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion);
// For demo purposes, wait for the sample to complete
rollbackTran2.Wait();
}
}
示例3: Main
//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;
class ContinuationSimpleDemo
{
// Demonstrated features:
// Task.Factory
// Task.ContinueWith()
// Task.Wait()
// Expected results:
// A sequence of three unrelated tasks is created and executed in this order - alpha, beta, gamma.
// A sequence of three related tasks is created - each task negates its argument and passes is to the next task: 5, -5, 5 is printed.
// A sequence of three unrelated tasks is created where tasks have different types.
// Documentation:
// http://msdn.microsoft.com/library/system.threading.tasks.taskfactory_members(VS.100).aspx
static void Main()
{
Action<string> action =
(str) =>
Console.WriteLine("Task={0}, str={1}, Thread={2}", Task.CurrentId, str, Thread.CurrentThread.ManagedThreadId);
// Creating a sequence of action tasks (that return no result).
Console.WriteLine("Creating a sequence of action tasks (that return no result)");
Task.Factory.StartNew(() => action("alpha"))
.ContinueWith(antecendent => action("beta")) // Antecedent data is ignored
.ContinueWith(antecendent => action("gamma"))
.Wait();
Func<int, int> negate =
(n) =>
{
Console.WriteLine("Task={0}, n={1}, -n={2}, Thread={3}", Task.CurrentId, n, -n, Thread.CurrentThread.ManagedThreadId);
return -n;
};
// Creating a sequence of function tasks where each continuation uses the result from its antecendent
Console.WriteLine("\nCreating a sequence of function tasks where each continuation uses the result from its antecendent");
Task<int>.Factory.StartNew(() => negate(5))
.ContinueWith(antecendent => negate(antecendent.Result)) // Antecedent result feeds into continuation
.ContinueWith(antecendent => negate(antecendent.Result))
.Wait();
// Creating a sequence of tasks where you can mix and match the types
Console.WriteLine("\nCreating a sequence of tasks where you can mix and match the types");
Task<int>.Factory.StartNew(() => negate(6))
.ContinueWith(antecendent => action("x"))
.ContinueWith(antecendent => negate(7))
.Wait();
}
}