简体   繁体   English

任务取消

[英]Task Cancellation

I want to wait until two tasks are done, but not in completed status. 我想等到两个任务完成,但没有完成状态。 The wait should over when the tasks are both in cancellation status. 当任务处于取消状态时,等待应该结束。

Does this line will continue when taskA and taskB will be canceld after activating cancellationToken? 激活cancellationToken后,当taskA和taskB将被取消时,这一行是否会继续?

Task.WaitAll(taskA, taskB); 

Thanks in advance. 提前致谢。

Yes, WaitAll will exit when both tasks are in a terminal state, whatever that terminal state is. 是的,当两个任务都处于终端状态时,无论终端状态如何, WaitAll都将退出。

However, it will complete by throwing an AggregateException if any of the tasks is faulted or cancelled. 但是,如果任何任务出现故障或被取消,它将通过抛出AggregateException来完成。 It will only complete normally (ie without an exception) if all of the tasks completed successfully. 如果所有任务都成功完成,它将只能正常完成(即没有例外)。 If you just want to keep going, you'll need to catch that exception. 如果你只是想继续前进,你需要抓住那个例外。 You can look at the InnerExceptions of the AggregateException to tell the difference between cancellation and faulting - or look at taskA and taskB themselves, of course. 您可以查看AggregateExceptionInnerExceptions来区分取消和故障 - 或者当然是查看taskAtaskB本身。

From the documentation , in the exceptions part: 文档中 ,在例外部分:

AggregateException At least one of the Task instances was canceled -or- an exception was thrown during the execution of at least one of the Task instances. AggregateException至少有一个Task实例被取消 - 或者 - 在执行至少一个Task实例期间抛出了异常。 If a task was canceled, the AggregateException contains an OperationCanceledException in its InnerExceptions collection. 如果任务被取消,则AggregateException在其InnerExceptions集合中包含OperationCanceledException。

Note that if you're using .NET 4.5 and async methods, you might want to use Task.WhenAll instead, which performs this waiting asynchronously - it returns a task which completes when the original tasks have completed. 请注意,如果您使用的是.NET 4.5和异步方法,则可能需要使用Task.WhenAll ,它会异步执行此操作 - 它会返回一个任务,该任务在原始任务完成时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM