c# - 使用 WhenAll 和 ContinueWith 时任务结果的顺序是什么

标签 c# asynchronous task-parallel-library

只是想知道使用WhenAll和ContinueWith时任务结果的顺序是怎样的。 这些结果是否保证与任务 ID 的顺序相同?

我写了下面的代码

public static async Task<string> PrintNumber(int number)
{
    return await Task.Delay(number*1000).ContinueWith(_=>
    {
        Console.WriteLine(number);return "TaskId:"+Task.CurrentId+" Result:"+number;
    });
}

public static void Main()
{

    Task.WhenAll(new[]
    {
        PrintNumber(3),
        PrintNumber(2),
        PrintNumber(1),

    }).ContinueWith((antecedent) => 
    { 
        foreach(var a in antecedent.Result)
        {
            Console.WriteLine(a);
        }
    });
}

然后在 linqpad 中多次运行得到相同的结果

1
2
3
TaskId:15 Result:3
TaskId:14 Result:2
TaskId:13 Result:1

1
2
3
TaskId:18 Result:3
TaskId:17 Result:2
TaskId:16 Result:1

最佳答案

通过那个特定的调用,Task[] 的参数-- 顺序保证。

其实根据Task.WhenAll(Task[])文档中没有提到任何顺序。但是如果你使用 Task.WhenAll(IEnumerable<Task<TResult>>)重载它读作 follows :

If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. The Result of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output task's Result will return an TResult[] where arr[0] == t1.Result, arr1 == t2.Result, and arr[2] == t3.Result).

关于c# - 使用 WhenAll 和 ContinueWith 时任务结果的顺序是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35176100/

相关文章:

c# - Topshelf 服务/应用卡在 "Creating"

c# - 从 MySQL ExecuteNonQuery 中获取 'Fatal Error'?

c# - 允许在 .ASCX 控件完成加载之前显示 .ASPX 页面吗?

ios - 使用 Parse 异步显示图像时出错

iphone - iOS 处理多个异步请求 : Send a Signal When All Requests Are Finished

c# - 如何在任务中取消 web 服务请求,并在取消时做一些事情

c# - 特定域的 DNS 解析失败。域与 nslookup 一起使用

javascript - 如何使用 Selenium 正确等待列表滚动?

c# - .NET 4.0 TPL 不是让 APM、EAP 和 BackgroundWorker 异步模式过时了吗?

c# - 将 TPL 与现有异步 API 结合使用