utilizing var tokenSource = new CancellationTokenSource(10_000);
var token = tokenSource.Token;
await foreach (var knowledge in Activity.WhenEach(duties).WithCancellation(token))
{
if (!tokenSource.TryReset())
token.ThrowIfCancellationRequested();
Console.WriteLine(await knowledge);
tokenSource.CancelAfter(10_000);
}
Within the previous code instance, CancellationTokenSource is used to create situations of a CancellationToken, which represents a cancellation token for use for cancellation of a process. The ThrowIfCancellationRquested technique known as to throw an OperationCanceledException if cancellation has been requested. The CancelAfter technique is used to schedule a cancel operation as soon as the required variety of milliseconds elapses.
Key takeaways
The Activity.WhenEach is a brand new asynchronous static technique launched in .NET 9 that addresses the constraints of the Activity.WhenAll and Activity.WhenAny strategies. By enabling the speedy processing of accomplished duties, it enhances the efficiency and scalability of your purposes significantly.
Be aware that you should use ThrowIfCancellationRequested from inside a process solely. On this case, you’ll not should deal with any exception explicitly. As an alternative, when this technique known as on a token occasion, the execution leaves the presently working process and the Activity.IsCancelled property is ready to True.