tvr
tvr

Reputation: 4575

Task await vs Task.WaitAll

In terms of parallelism are these equivalent?

async Task TestMethod1()
{
    Task<int> t1 = GetInt1();
    Task<int> t2 = GetInt2();
    await Task.WhenAll(t1, t2); 
}

async Task TestMethod2()
{
    Task<int> t1 = GetInt1();
    await GetInt2();
    await t1;
}

In TestMethod2, I am mainly interested in understanding whether GetInt1() starts executing while awaiting GetInt2().

Upvotes: 2

Views: 1042

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456487

Yes, in terms of "parallelism" (actually concurrency), they are pretty much the same.

In particular, the TAP docs state that returned tasks are "hot", that is:

All tasks that are returned from TAP methods must be activated... Consumers of a TAP method may safely assume that the returned task is active

So, your code is starting the asynchronous operations by calling their methods. The tasks they return are already in progress. In both examples, both tasks are running concurrently.

It doesn't matter terribly much whether you use two awaits or a single await Task.WhenAll. I prefer the Task.WhenAll approach because IMO it more clearly communicates the intent of concurrency. Also, it only interrupts the source context (e.g., UI thread) once instead of twice, but that's just a minor concern.

Upvotes: 1

Related Questions