问题
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