Task.WhenAll中是否有任务完成时的回调 [英] Is there a callback for when a task is completed in Task.WhenAll
问题描述
假设我有以下内容:
IEnumerable<Task<TimeSpan>> tasks = //...
TimeSpan[] results = await Task.WhenAll(tasks);
// Handle results
等到我可以处理所有任务必须完成的结果时.
By the time I can handle the results all the task must have finished.
是否有一种方法可以按需处理每个结果??
Is there a way to handle each result on demand?
就像注册一个将在任务完成时执行的委托/回调一样:
Like registering a delegate / callback that will get executed when a task is completed:
IEnumerable<Task<TimeSpan>> tasks = //...
await Task.WhenAll(tasks, result =>
{
// A task has finished. This will get executed.
// result is of type TimeSpan
});
推荐答案
有没有一种方法可以按需处理每个结果?
Is there a way to handle each result on demand?
是的,您使用WhenAny
而不是WhenAll
...或在每个任务上调用ContinueWith
.
Yes, you use WhenAny
instead of WhenAll
... or call ContinueWith
on each task.
例如,对于WhenAny
方法:
ISet<Task<TimeSpan>> tasks = new HashSet<Task<TimeSpan>>(...);
while (tasks.Count != 0)
{
var task = await Task.WhenAny(tasks);
// Use task here
tasks.Remove(task);
}
您可以使用另一个选项,将原始任务序列转换为按顺序完成但给出相同结果的任务序列.详细信息在此博客帖子,但结果是您可以使用:
There's another option you could use, where you transform the original sequence of tasks into a sequence of tasks which completes in order, but giving the same results. Details are in this blog post, but the result is that you can use:
foreach (var task in tasks.InCompletionOrder())
{
var result = await task;
// Use the result
}
这篇关于Task.WhenAll中是否有任务完成时的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!