9.9 C
New York
Thursday, October 17, 2024

How you can use Process.WhenEach in .NET 9




utilizing var tokenSource = new CancellationTokenSource(10_000);
var token = tokenSource.Token;
await foreach (var knowledge in Process.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 cases of a CancellationToken, which represents a cancellation token for use for cancellation of a process. The ThrowIfCancellationRquested technique is named to throw an OperationCanceledException if cancellation has been requested. The CancelAfter technique is used to schedule a cancel operation as soon as the desired variety of milliseconds elapses.

Key takeaways

The Process.WhenEach is a brand new asynchronous static technique launched in .NET 9 that addresses the restrictions of the Process.WhenAll and Process.WhenAny strategies. By enabling the fast processing of accomplished duties, it enhances the efficiency and scalability of your purposes significantly.

Word that you should utilize ThrowIfCancellationRequested from inside a process solely. On this case, you’ll not need to deal with any exception explicitly. As a substitute, when this technique is named on a token occasion, the execution leaves the presently operating process and the Process.IsCancelled property is ready to True.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles