简体   繁体   English

动作块<T> vs Task.WhenAll

[英]ActionBlock<T> vs Task.WhenAll

I would like to know what is the recommended way to execute multiple async methods in parallel?我想知道并行执行多个异步方法的推荐方法是什么?

in System.Threading.Tasks.Dataflow we can specify the max degree of parallelism but unbounded is probably the default for Task.WhenAll too ?在 System.Threading.Tasks.Dataflow 中,我们可以指定最大并行度,但无界可能也是 Task.WhenAll 的默认值?

this :这个:

var tasks = new List<Task>();
foreach(var item in items)
{
    tasks.Add(myAsyncMethod(item));
}
await Task.WhenAll(tasks.ToArray());

or that :或者:

var action = new ActionBlock<string>(myAsyncMethod, new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
            BoundedCapacity = DataflowBlockOptions.Unbounded,
            MaxMessagesPerTask = DataflowBlockOptions.Unbounded
        });
foreach (var item in items) { }
{
     action.Post(item);
}
action.Complete();

await action.Completion;

I would like to know what is the recommended way to execute multiple async methods in parallel?我想知道并行执行多个异步方法的推荐方法是什么?

Side note: actually not parallel , but concurrent .旁注:实际上不是parallel ,而是concurrent

in System.Threading.Tasks.Dataflow we can specify the max degree of parallelism but unbounded is probably the default for Task.WhenAll too ?在 System.Threading.Tasks.Dataflow 中,我们可以指定最大并行度,但无界可能也是 Task.WhenAll 的默认值?

As someone commented, Task.WhenAll only joins existing tasks;正如有人评论的, Task.WhenAll只加入现有的任务; by the time your code gets to Task.WhenAll , all the concurrency decsions have already been made.当您的代码到达Task.WhenAll ,所有并发决策都已经完成。

You can throttle plain asynchronous code by using something like SemaphoreSlim .您可以使用SemaphoreSlim东西来限制普通的异步代码。

The decision of whether to use asynchronous concurrency directly or TPL Dataflow is dependent on the surrounding code.是直接使用异步并发还是 TPL Dataflow 的决定取决于周围的代码。 If this concurrent operation is just called once asynchronously, then asynchronous concurrency is the best bet;如果这个并发操作只是异步调用一次,那么异步并发是最好的选择; but if this concurrent operation is part of a "pipeline" for your data, then TPL Dataflow may be a better fit.但如果此并发操作是数据“管道”的一部分,那么 TPL Dataflow 可能更合适。

Both methods are acceptable and the choice should be governed by your requirements as you can see Dataflow gives you a lot of configurability that you would otherwise have to implement manually when using Tasks directly.这两种方法都是可以接受的,选择应该由您的需求决定,因为您可以看到 Dataflow 为您提供了很多可配置性,否则您在直接使用 Tasks 时必须手动实现这些可配置性。

Note that in both situations the Task Pool will be responsible for enqueuing and running the tasks so the behaviour should remain the same.请注意,在这两种情况下,任务池都将负责排队和运行任务,因此行为应保持不变。

Dataflow is good at chaining together groups of composable asynchronous operations whereas using tasks gives you finer grained control. Dataflow 擅长将可组合的异步操作组链接在一起,而使用任务可以提供更细粒度的控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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