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.