Stats

1888 Contributors: 37
2017-06-18
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Async-Await

Download c# eBook

Introduction

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 awaitkeyword.

Remarks

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 awaited, 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.

Related Examples