Does Task.WhenAll run Tasks in background thread parallel

倾然丶 夕夏残阳落幕 提交于 2019-12-10 17:53:47

问题


Are the following 2 code fragments do the same?

//--------------------------------------------------
1.
//--------------------------------------------------

var producer = Task.Run(async () =>
{
    await bar.ReadDataAsync();
});

var consumer = Task.Run(async () =>
{
    await bar.WriteDataAsync();
});


await Task.WhenAll(consumer, producer);

//--------------------------------------------------
2.
//--------------------------------------------------

await Task.WhenAll(bar.ReadDataAsync(), bar.WriteDataAsync());

回答1:


Task.WhenAll does not run the tasks. No tasks are started by this method.

What Task.WhenAll does do is return a new Task that only completes when all the original tasks have completed.

From msdn

Task.WhenAll Method

.NET Framework 4.6 and 4.5

Creates a task that will complete when all of the supplied tasks have completed.

https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall%28v=vs.110%29.aspx

In your example, you have called Task.Run. This is a request that you would like to run a unit of work asynchronously. However, the thread affinity is not guaranteed. Both units of work may run synchronously - that is up to the default TaskScheduler to decide.




回答2:


There's no magic in Task.WhenAll - it's a method like any other.

As such, first all its arguments are evaluated, and only after that the method itself is executed. So yeah, you get parallel execution.



来源:https://stackoverflow.com/questions/33891586/does-task-whenall-run-tasks-in-background-thread-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!