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 ?
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;
Parallel.ForEach()
? – BouieTask.WhenAll
code you've shown has nothing to do with executing tasks in parallel - any decisions about the use of e.g. thread pool threads, parallelism, etc, is happening withinmyAsyncMethod
which is (presumably) returning hotTask
s. – QuicheBoundedCapacity = DataflowBlockOptions.Unbounded
is the default. By including it explicitly in the options you open the possibility that you, or someone else, in the future decides to configure it to a better value. And then your program will start behaving oddly, and you'll spent a day and a half trying to figure out why. – OntarioPost
method drops items to the floor when the receiving block refuses to accept them because its buffer has become full. To avoid this unpleasant situation, it is better to be proactive and useawait action.SendAsync(item)
, oraction.SendAsync(item).Wait()
if you are not inside an asynchronous method. The overhead ofSendAsync
is negligible. – Ontario