Home >Backend Development >C++ >How Can I Efficiently Run Multiple Async Tasks in Parallel using .NET 4.5?
.NET 4.5 presents challenges when managing concurrent, long-running tasks. While Task.Run()
offers a basic approach, it lacks the efficiency and elegance of leveraging asynchronous features fully.
A superior solution utilizes async
/await
to create truly asynchronous Sleep
methods, allowing for interruptions and efficient resumption. Task.WhenAll()
concurrently awaits the completion of multiple tasks.
Improved Code Example:
<code class="language-csharp">public static async Task Go() { Console.WriteLine("Initiating tasks"); Task<int> task1 = SleepAsync(5000); Task<int> task2 = SleepAsync(3000); await Task.WhenAll(task1, task2); int totalSleepTime = task1.Result + task2.Result; Console.WriteLine($"Total sleep time: {totalSleepTime} ms"); } private static async Task<int> SleepAsync(int ms) { Console.WriteLine($"Sleeping for {ms} ms"); await Task.Delay(ms); Console.WriteLine($"Sleep of {ms} ms COMPLETE"); return ms; }</code>
This enhanced code uses async
and Task.Delay()
for non-blocking delays within SleepAsync
. Go
initiates both tasks concurrently via Task.WhenAll()
, enabling parallel execution. Results are accessed using the Result
property upon completion.
The above is the detailed content of How Can I Efficiently Run Multiple Async Tasks in Parallel using .NET 4.5?. For more information, please follow other related articles on the PHP Chinese website!