Async/Await
Explore the fundamentals of async and await in C# to manage asynchronous programming. Understand how the compiler-generated state machine works, the role of awaitable tasks, and how asynchronous methods execute with concurrency control. Learn practical conversion from synchronous to asynchronous methods and how to handle task completion and threading behavior.
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 ...