CancellationTokenSource cts = new CancellationTokenSource(); Task t = new Task<int>(()=>Sum(1000,cts.Token),cts.Token); t.Start(); Thread.Sleep(100); cts.Cancel(); try { Console.WriteLine(t.Result); } catch (AggregateException ex) { //如果是取消产生的异常,则忽略 x.Handle(ex=>ex is OperationCanceledException; Console.WriteLine("操作取消"); }
Static intSum(int n, CancellationToken ct) { int sum=0; for(int i =1;i<=n;i++) { //检查是否已取消并抛出异常 ct.ThrowIfCancellationRequested(); sum+=i; } return sum; }
延续任务
Task支持在任务完成后继续执行其它任务,并可指定延续任务的执行条件
1 2
Task<int> t = Task.Run(()=>Sum(1000,cts.Token),cts.Token); t.ContinueWith(task=>Console.WriteLine(task.Result,TaskContinuationOptions);
其中t作为参数被传递到延续任务中
父子任务
可以在一个Task中包含若干个子任务,只有在所有子任务完成后父任务才会被标记为完成状态
1 2 3 4 5 6 7 8
Task<int[]> parent=new Task<int[]>(()=>{ var results=newint[3]; new Task(()=>results[0]=Sum(1000),TaskCreationOptions.AttachedtoParent).Start(); new Task(()=>results[1]=Sum(2000),TaskCreationOptions.AttachedtoParent).Start(); new Task(()=>results[2]=Sum(3000),TaskCreationOptions.AttachedtoParent).Start(); return results; }); parent.Start();