In C#, a method declared async
won't block within a synchronous process, in case of you're using I/O based operations (e.g. web access, working with files, ...). The result of such async marked methods may be awaited via the use of the await
keyword.
An async
method can return void
, Task
or Task<T>
.
The return type Task
will wait for the method to finish and the result will be void
. Task<T>
will return a value from type T
after the method completes.
async
methods should return Task
or Task<T>
, as opposed to void
, in almost all circumstances. async void
methods cannot be await
ed, which leads to a variety of problems. The only scenario where an async
should return void
is in the case of an event handler.
async
/await
works by transforming your async
method into a state machine. It does this by creating a structure behind the scenes which stores the current state and any context (like local variables), and exposes a MoveNext()
method to advance states (and run any associated code) whenever an awaited awaitable completes.