Task.WhenAll在后台线程中并行运行Task吗? [英] 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
不运行任务.此方法不会启动任何任务.
Task.WhenAll
does not run the tasks. No tasks are started by this method.
Task.WhenAll
要做的是返回一个新的Task
,该Task
仅在所有原始任务均已完成时完成.
What Task.WhenAll
does do is return a new Task
that only completes when all the original tasks have completed.
来自msdn
Task.WhenAll方法
.NET Framework 4.6和4.5
创建一个任务,当所有提供的任务都完成时,该任务将完成 完成.
Creates a task that will complete when all of the supplied tasks have completed.
https://msdn.microsoft.com/zh-CN/library/system.threading.tasks.task.whenall%28v=vs.110%29.aspx
在您的示例中,您呼叫了Task.Run
.这是您希望异步运行工作单元的请求.但是,不能保证线程亲和性.这两个工作单元可以同步运行-由默认的TaskScheduler
决定.
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.
这篇关于Task.WhenAll在后台线程中并行运行Task吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!