如何取消Task.WhenAll? [英] How can I cancel Task.WhenAll?

查看:153
本文介绍了如何取消Task.WhenAll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在使用以下代码来等待一组任务完成。但是,我现在遇到这样的情况,我希望能够最好通过取消令牌来取消/中止WhenAll调用。我该怎么办?

Currenly using the following code to wait for a collection of tasks to complete. However, I now have a situation where I want to be able to cancel/abort the WhenAll call, via a cancellation token preferably. How would I go about that?

  Dim TaskCollection As New List(Of Tasks.Task)
  For x As Integer = 1 To Threads
    Dim NewTask As Tasks.Task = TaskHandler.Delegates(DelegateKey).Invoke(Me, Proxies, TotalParams).ContinueWith(Sub() ThreadFinished())
    TaskCollection.Add(NewTask)
  Next

  Await Tasks.Task.WhenAll(TaskCollection)

我假设它会用,但与下一部分代码类似,但是我不确定'XXX'中会用到什么。

I'm assuming it's going to but something along the lines of the next bit of code, but I'm not sure what would go in 'XXX'.

Await Tasks.Task.WhenAny(Tasks.Task.WhenAll(TaskCollection), XXX)


推荐答案

使用 TaskCompletionSource< T> 为尚未具有异步API的某些异步条件创建任务。使用 CancellationToken.Register 将现代的基于CancellationToken的取消系统挂接到另一个取消系统中。您的解决方案只需要结合这两个即可。

Use TaskCompletionSource<T> to create a task for some asynchronous condition that does not already have an asynchronous API. Use CancellationToken.Register to hook the modern CancellationToken-based cancellation system into another cancellation system. Your solution just needs to combine these two.

我有一个 CancellationToken.AsTask()我的AsyncEx库中的扩展方法,但是您可以这样编写自己的方法:

I have a CancellationToken.AsTask() extension method in my AsyncEx library, but you can write your own as such:

<System.Runtime.CompilerServices.Extension> _
Public Shared Function AsTask(cancellationToken As CancellationToken) As Task
  Dim tcs = New TaskCompletionSource(Of Object)()
  cancellationToken.Register(Function() tcs.TrySetCanceled(), useSynchronizationContext := False)
  Return tcs.Task
End Function

用法与您一样预期:

Await Task.WhenAny(Task.WhenAll(taskCollection), cancellationToken.AsTask())

这篇关于如何取消Task.WhenAll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆