如何通过 Tasks.WaitAll() 使用 CancellationToken

How to use the CancellationToken with Tasks.WaitAll()

我想知道如何使用以 CancellationToken 作为参数的 Task.WaitAll 重载,例如https://msdn.microsoft.com/en-us/library/dd321573%28v=vs.110%29.aspx

文档说 CancellationToken 参数是 "A CancellationToken to observe while waiting for the tasks to complete."

因为 Task.WaitAll 是一个阻塞操作,你怎么可能 "observe" 在那个操作期间呢?此外,它说 "The cancellationToken argument is used to cancel the wait operation. If it is canceled, the Wait returns false." 但它也在其他地方说当 CancellationToken 被取消时会抛出 OperationCanceledException ,这意味着 Task.WaitAll 不会 return true false.

我要么遗漏了一些非常简单的东西,要么文档有问题。无论哪种方式,我都非常困惑。我的最终目标是能够等待多个任务完成或优雅地取消它们(通过正确使用 CancellationToken),如果它们在特定时间段内没有完成。

这与我的 post here 有关,但是这次,我正在编写异步代码并且可以观察到取消标记。

Since Task.WaitAll is a blocking operation, how could you possibly "observe" it during that operation?

你不是观察者;这是 Task.WaitAll 方法。

Furthermore, it says "The cancellationToken argument is used to cancel the wait operation. If it is canceled, the Wait returns false." but then it also says elsewhere that a OperationCanceledException is thrown when the CancellationToken is cancelled, meaning Task.WaitAll doesn't return true or false.

这似乎是文档中的一个错误。如果在任务完成或等待被取消之前指定的超时已经过去,则它 returns 为 false。

Who cancels it?

通常,一些代码 运行 在另一个线程上,因为当前线程已经忙于等待任务完成。或者您可以调用 CancellationTokenSource.CancelAfter 来指定一个超时时间,之后令牌将被取消。