Understanding async and await, Task.WaitAll, Task.Run, and parallelism: part 2

So another issue with async, await came up. I was using Task.WaitAll to make it parallel, but it wasn’t parallel.

var task1 = Method1();
var task2 = Method2();
Task.WhenAll(task1, task2)

Now Method1() and Method2() had some code that took some time. Now my code was making some large web service calls, but we can demonstrate this more easily just by sleeping for 10 seconds.

public async Task Method1()
{
    Thread.Sleep(10000); // Ten seconds
}

public async Task Method2()
{
    await Task.Delay(10000); // 10 second task
}

I expected these to run in parallel, but they didn’t. Let me explain why.

When calling a method that returns task, it doesn’t actually return until the first await. Notice Method1() doesn’t have an await. So Method1() will run synchronously until the first await.

Method2(), however, is pretty much the same, but does have an await. So it returns immediately.

Getting parallelism is easy. Wrap the method in Task.Run().

public async Task Method1()
{
Task.Run(Thread.Sleep, 10000)); // Ten seconds
}

Leave a Reply

How to post code in comments?