Task.WhenAll中是否有任务完成时的回调

编程入门 行业动态 更新时间:2024-10-21 18:34:49
本文介绍了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中是否有任务完成时的回调

本文发布于:2023-11-12 20:25:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   Task   WhenAll

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!