Home >Backend Development >C++ >How Can I Efficiently Run Multiple Async Tasks in Parallel using .NET 4.5?

How Can I Efficiently Run Multiple Async Tasks in Parallel using .NET 4.5?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-13 06:27:41940browse

How Can I Efficiently Run Multiple Async Tasks in Parallel using .NET 4.5?

Efficient Parallel Async Task Execution in .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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn