async, await, and Task
In this section, we will be looking at the performance differences between running methods synchronously, using Task.Run
, and asynchronously. An asynchronous method is identified by the async
keyword.
The await
keyword informs the runtime to wait at the specified line until the current task has been completed. It can only be used with a method that is prefixed with the async
keyword.
The Task Parallel Library (TPL) can be found in the System.Threading.Tasks
namespace. A task encapsulates threading in order to maximize the use of multiple cores on computer hardware.
Let's write a simple project to benchmark three different ways of calling a method. We will call the method synchronously using Task.Run
, and asynchronously using async/await
. We will be using BenchmarkDotNet
to see how each method call type performs. We aim to show the performance advantage of using asynchronous calls over synchronous and Task.Run
calls.
We perform the following steps...