Using async, await, and WhenAll
In this section, we will write some example code that demonstrates the use of async
, await
, and WhenAll
and the effect on execution time.
If you have multiple tasks that are being executed in a method and you await
each task, your code will work asynchronously, and the execution time will be expensive. You can circumvent this time expense with improved performance by using WhenAll
to await
all completed tasks before continuing. In the code we will be writing, you will see how WhenAll
reduces the time taken to execute two asynchronous methods within a function when compared to awaiting each task in turn.
Let's work our way through the following tasks:
- In the
Benchmarks
class still, add the following asynchronous method, which waits300
milliseconds before returning anint
:private async Task<int> TaskOne() { await Task.Delay(300); return 100; }
The TaskOne
method is the...