简体   繁体   中英

Does Task.WhenAll run Tasks in background thread parallel

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());

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM