Description
The ForEachTaskAsync
method is an extension method for processing a collection of items asynchronously. It allows you to execute a specified asynchronous function on each element of the collection concurrently, with a limit on the number of tasks that can run simultaneously. This method is useful for managing resources and ensuring that too many tasks are not executed at once, which could lead to resource exhaustion.
Usage
To use the ForEachTaskAsync
method, you need to provide the following parameters:
source
: An IEnumerable<T>
representing the collection of items to process.
body
: A Func<T, Task>
delegate that defines the asynchronous operation to perform on each item.
maxRunning
: An int
specifying the maximum number of tasks that can run concurrently.
token
: A CancellationToken
to observe while waiting for tasks to complete. This allows the operation to be cancelled.
Call this method as an extension method on any IEnumerable<T>
collection.
Example
// Example usage of ForEachTaskAsync
var items = new List<int> { 1, 2, 3, 4, 5 };
await items.ForEachTaskAsync(async item =>
{
// Simulate an asynchronous operation
await Task.Delay(1000);
Console.WriteLine($"Processed item: {item}");
}, maxRunning: 2, token: CancellationToken.None);