Parallel.ForEachAsync is a method in the System.Threading.Tasks.Parallel class in .NET that provides a way to execute asynchronous tasks in parallel. The method takes several parameters:
The input collection: It could be an array, a list, or any enumerable collection of objects.
The delegate function: It's an async function that takes an input object and returns an output object.
The async cancellation token: This parameter is optional and allows you to cancel the execution of the parallel tasks at any time.
The options parameter: It could include options like MaxDegreeOfParallelism, which specifies the maximum number of tasks that could be executed in parallel.
The Parallel.ForEachAsync method returns a Task object that you can await to get the results of the asynchronous tasks.
Here is an example of how Parallel.ForEachAsync can be employed:
var inputs = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };
var cancellation = new CancellationToken();
var results = await Parallel.ForEachAsync(inputs, async (input, token) =>
{
// Execute your asynchronous task
await Task.Delay(1000);
// Return the output value
return $"Result for input {input}";
}, options, cancellation);
// Process the results
foreach (var result in results)
{
Console.WriteLine(result);
}
In this example, we iterate over a list of integers and execute a delay of 1000 milliseconds asynchronously. We also specify a maximum degree of parallelism of 4 and an optional cancellation token. Finally, we await the results and print them to the console.
Asked: 2023-03-30 11:00:00 +0000
Seen: 17 times
Last updated: Jul 13 '22