1
private static async Task Main()
    {
        Console.Clear();
        Console.WriteLine("start");
        await MyMethodAsync();
    }

    private static async Task MyMethodAsync()
    {
        const int count = 10;
        Task<string> loopATask = Task.Run(() => LoopA(count));
        Task<string> loopBTask = Task.Run(() => LoopB(count));
        string resultA = await loopATask;
        string resultB = await loopBTask;
        Console.WriteLine(resultA + resultB);
    }


    public static string LoopA(int count)
    {
        Task.Delay(2000);
        return "LoopA has finished ";
    }

    public static string LoopB(int count)
    {
        Task.Delay(1000);
        return "LoopB has finished ";
    }

Expected Output : 2 second delay before writing resultA + resultB

Actual Output: resulA + resultB is printed instantly

electro
  • 55
  • 5

1 Answers1

4

Task.Delay is an async operation which should be awaited:

Creates a task that will complete after a time delay.

So if you don't await it's basically fire and forget operation with an unobserved result.

Change corresponding methods to:

public static async Task<string> LoopA(int count)
{
    await Task.Delay(2000);
    return "LoopA has finished ";
}

public static Task<string> LoopB(int count)
{
    await Task.Delay(1000);
    return "LoopB has finished ";
}

And now you can also scrap Task.Run as not needed:

Task<string> loopATask = LoopA(count);
Task<string> loopBTask = LoopB(count);

Also note that there are advantages in using Task.WhenAll over multiple sequential await's.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132