SHAREDHow to use Task.WhenEach in .NET 9

How to use Task.WhenEach in .NET 9

How to use Task.WhenEach in .NET 9


using var tokenSource = new CancellationTokenSource(10_000);
var token = tokenSource.Token;
await foreach (var data in Task.WhenEach(tasks).WithCancellation(token))
{
    if (!tokenSource.TryReset()) 
        token.ThrowIfCancellationRequested();
    Console.WriteLine(await data);
    tokenSource.CancelAfter(10_000);
}

In the preceding code example, CancellationTokenSource is used to create instances of a CancellationToken, which represents a cancellation token to be used for cancellation of a task. The ThrowIfCancellationRquested method is called to throw an OperationCanceledException if cancellation has been requested. The CancelAfter method is used to schedule a cancel operation once the specified number of milliseconds elapses.

Key takeaways

The Task.WhenEach is a new asynchronous static method introduced in .NET 9 that addresses the limitations of the Task.WhenAll and Task.WhenAny methods. By enabling the immediate processing of completed tasks, it enhances the performance and scalability of your applications considerably.

Note that you can use ThrowIfCancellationRequested from within a task only. In this case, you will not have to handle any exception explicitly. Instead, when this method is called on a token instance, the execution leaves the currently running task and the Task.IsCancelled property is set to True.

Latest news

14 Best Dark WordPress Themes (Free and Premium)

Dark WordPress themes have that modern and stylish look that can bring a unique touch to your website.There are...

InMotion Hosting Upgrades VPS Plans for Superior Performance

InMotion Hosting now offers increased RAM, advanced SSD storage options, and expanded bandwidth on its VPS Hosting plans as...

Cloud Backups Comparison: CrashPlan vs. Backblaze

In the ever-evolving world of cloud backup services, CrashPlan and Backblaze emerge as two major players vying for dominance. Both...

Juggling On-Premises and Cloud Solutions for the Best Performance: Hybrid Hosting!

In this chameleon-like digital era, businesses are on a quest to find ingenious methods to...

Where To Watch The Office Australia in 2024

Where To Watch The Office Australia in 2024 ...

WasmGC and the future of front-end Java development

Is WasmGC ready for production use? I asked Steiner about using the WasmGC extension in production apps and he noted...

Must read

Top 10 CIO Trends for 2019

As we get ready to close out 2018 and...

Are the cloud wars over or just getting started?

One of the biggest opportunities for enterprises large and...

You might also likeRELATED
Recommended to you