Async/Await
This lesson introduces the async and await keywords and works through an example using the two.
We'll cover the following
Async/Await
The language keywords async
and await
are at the center of asynchronous programming in C#. Let's delve into how they work:
Async
The async
keyword can be added to the signature of a method. It is syntactic sugar that hides away a lot of complexity that gets added for an async
marked method. Under the hood, the compiler creates a state machine for an async method. We'll shortly explain the working of the state machine.
A method marked async has restrictions on what it can return. We can return the following from an async
method:
void
Task
Task<T>
Starting in C# 7.0, we can also return generic types that satisfy the requirements for a type to be awaitable (more on that later).
Asynchronous methods either return tasks or nothing. Tasks are awaitable. Note that when a type is said to be awaitable, it implies that it can be legally used as an argument to the await
expression.
Synchronous Sleep to Asynchronous Sleeep
To understand async/await better, we'll take a trivial program that executes synchronously and convert it into asynchronous execution. Along the way, we'll see how the various concepts tie-up together. In the code widget below, we have a method sleep()
that performs a Thread.Sleep()
for three seconds synchronously.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.