Friday, December 13, 2024

Activity.WhenEach in .NET 9 allows you to execute a series of activities concurrently and then wait for the first one that completes. The WhenEach method takes an observable sequence as input, and it returns another observable sequence that contains the results of all the activities. When you use Activity.WhenEach, you need to make sure that the observable sequence is properly set up so that each activity can be executed concurrently. This means that the activities should not be dependent on each other’s completion. Here are a few things to keep in mind when using WhenEach: 1. The activities in your observable sequence must not throw exceptions. If any of them do, the exception will propagate through the pipeline and cause an exception. 2. You can use WhenEach with both Activity and Task-based asynchronous programming. 3. It’s important to properly handle cancellation tokens when using WhenEach to ensure that activities are canceled correctly. Here’s a simple example of how you might use WhenEach: “`csharp var activities = new[] { Activity.Run(“Task 1”, () => { /* some code */ }), Activity.Run(“Task 2”, () => { /* some code */ }), Activity.Run(“Task 3”, () => { /* some code */ }) }; var results = await Activity.WhenEach(activities); “`


using var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken(source: TimeSpan.FromMilliseconds(10_000)));
var token = tokenSource.Token;
await foreach (var knowledge in Activity.WhenEach(duties).WithCancellation(token))
{
    while (!tokenSource.IsCancellationRequested)
    {
        if (await tokenSource.WaitHandle.WaitOneAsync())
        {
            break;
        }
        Console.WriteLine(await knowledge);
    }
}

Within existing code instances, CancellationTokenSource is leveraged to generate scenarios involving CancellationToken, thereby enabling the representation of a mechanism for canceling an ongoing activity. The ThrowIfCancellationRequested technique is used to throw an OperationCanceledException when cancellation has been requested. The CancelAfter technique schedules a cancellation operation after a specified number of milliseconds have elapsed.

Key takeaways

When .NET 6 introduced the WhenEach method, it revolutionized the way developers handle parallel workflows with Activities. This groundbreaking static approach finally addressed the limitations of the long-established Activity.WhenAll and Activity.WhenAny methods. By streamlining the completion of tasks, it substantially boosts the efficacy and scalability of your operations.

When using cancellation tokens within an asynchronous operation, utilize ThrowIfCancellationRequested exclusively within the activity where the token was created. You’ll typically not need to handle any exceptions explicitly in this scenario. When this technique, known as cancellation, occurs on an occasional basis, the system’s execution temporarily abandons its current task and sets the Activity.IsCancelled property to True.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles