Home > Backend Development > C++ > How Can I Run Two Async Tasks Concurrently and Get Their Results in .NET 4.5?

How Can I Run Two Async Tasks Concurrently and Get Their Results in .NET 4.5?

Linda Hamilton
Release: 2025-01-13 07:34:42
Original
488 people have browsed it

How Can I Run Two Async Tasks Concurrently and Get Their Results in .NET 4.5?

Efficiently Executing and Retrieving Results from Concurrent Async Tasks in .NET 4.5

This guide demonstrates a streamlined method for running two asynchronous tasks concurrently within the .NET 4.5 framework and efficiently collecting their respective results. Previous approaches using Task.Run() and Thread.Sleep() are less than ideal for asynchronous operations.

Here's an improved solution:

<code class="language-csharp">async Task<int> LongTask1()
{
    // Simulate a long-running operation
    await Task.Delay(1000); // Replace with your actual asynchronous task
    return 0;
}

async Task<int> LongTask2()
{
    // Simulate a long-running operation
    await Task.Delay(1500); // Replace with your actual asynchronous task
    return 1;
}

// ... within your main method ...
{
    Task<int> task1 = LongTask1();
    Task<int> task2 = LongTask2();

    await Task.WhenAll(task1, task2);

    // Access results after both tasks have completed
    int result1 = task1.Result;
    int result2 = task2.Result;
    // ... process result1 and result2 ...
}</code>
Copy after login

This refined code leverages the power of async/await:

  • LongTask1 and LongTask2 are asynchronous methods representing your long-running operations. Remember to replace Task.Delay() with your actual asynchronous logic.
  • Task.WhenAll(task1, task2) ensures both tasks complete before proceeding, effectively synchronizing the results.
  • task1.Result and task2.Result provide access to the returned values of each task once they have finished executing.

This approach offers a cleaner, more efficient, and truly asynchronous solution compared to previous methods, eliminating the need for Task.Run() and inefficient blocking calls like Thread.Sleep(). It's the recommended way to handle concurrent asynchronous tasks in .NET 4.5.

The above is the detailed content of How Can I Run Two Async Tasks Concurrently and Get Their Results in .NET 4.5?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template