Async Refactoring / Waiting for Parallel Processing

Still going through the learning phase with C # and came across a question in which I needed help. Given the following code:

private async Task<String> PrintTask()
{
    await Task.Delay(3000);
    return "Hello";
}

private async void SayHelloTwice()
{
    string firstHello = await PrintTask();
    string secondHello = await PrintTask();

    Console.WriteLine(firstHello);
    Console.WriteLine(secondHello);
}

Now SayHelloTwice () will take 6 seconds. However, I want the search tasks to run in parallel in order to complete only 3 seconds. How would I reorganize my code to achieve this? Thank!

+4
source share
3 answers

The right way to do this (without the risk of blocking) is to use Task.WhenAll

private async void SayHelloTwice()
{
    string[] results = await Task.WhenAll(
        PrintTask(),
        PrintTask());

    Console.WriteLine(results[0]);
    Console.WriteLine(results[1]);
}

" " , . , .

, Task.Result Task.WaitAll, ( ) Task.

, , Task , .

, "Task" Outter Thread .

"" .

.

+4

, . :

private async void SayHelloTwice()
{
    // Start the tasks, don't wait
    Task<string> firstHello = PrintTask();
    Task<string> secondHello = PrintTask();

    // Wait for results
    string firstResult = await firstHello;
    string secondResult = await secondHello;

    // Print results
    Console.WriteLine(firstResult);
    Console.WriteLine(secondResult);
}

, PrintTask() , await, async, firstHello. secondHello. .

. , , Task.WhenAll

+3
  • Task.WhenAll .
  • Task, void (async/await - vs void?):

    private static async Task SayHelloTwice()
    {
        var hellos = await Task.WhenAll(PrintTask(), PrintTask());
        Console.WriteLine(hellos[0]);
        Console.WriteLine(hellos[1]);
    }
    
+3

All Articles