8.3 C
New York
Friday, November 22, 2024

How one can use Job.WhenEach in .NET 9




utilizing var tokenSource = new CancellationTokenSource(10_000);
var token = tokenSource.Token;
await foreach (var knowledge in Job.WhenEach(duties).WithCancellation(token))
{
    if (!tokenSource.TryReset()) 
        token.ThrowIfCancellationRequested();
    Console.WriteLine(await knowledge);
    tokenSource.CancelAfter(10_000);
}

Within the code instance above, CancellationTokenSource is used to instantiate CancellationToken, which represents a cancellation token for use for canceling a activity. The ThrowIfCancellationRquested technique is known as to throw an OperationCanceledException if cancellation was requested. The CancelAfter technique is used to schedule a cancel operation after the desired variety of milliseconds has handed.

Key takeaways

Job.WhenEach is a brand new asynchronous static technique launched in .NET 9 that addresses the restrictions of the Job.WhenAll and Job.WhenAny strategies. By enabling fast processing of accomplished duties, you considerably enhance the efficiency and scalability of your purposes.

Observe that you should use ThrowIfCancellationRequested solely from a activity. On this case, you will not need to deal with any exceptions explicitly. As a substitute, when this technique is known as on a token occasion, execution abandons the at the moment executing activity and the Job.IsCancelled property is about to True.

Related Articles

Latest Articles