Asynchronous Programming - Async And Await
Intro
My notes on C#'s asynchronous programming constructs
Documentation
Tips and TidBits
Asynchronous operations begin the work and return a Task that represents the ongoing work.
You can only use await in an async method, and Main cannot be async.
A method which uses
await
must have theasync
attribute
public async Task MyAsyncMethod()
{
await SomeAsyncTask;
MoreWorkToBeDone;
}
Using the
async
attribute on a method does not make it run on a separate thread.Once the method reaches the
await
, it examins if the task (eg SomeAsyncTask) has already completed.If it has completed , then it continues to the next statement (MoreWorkToBeDone), just alike a synchronous statement.
If it hasn’t completed, then
It instructs the task (eg
SomeAsyncTask
) that it needs to execute the code that follows when it completes its own execution.The method returns immediately (ie, it doesn’t execute
MoreWorkToBeDone
).Later, when the task (eg
SomeAsyncTask
) completes, it can execute the rest of the async method.
Async methods can return: Task<T>, Task, or void.
In almost all cases, you want to return Task<T> or Task. Avoid returning
void
.eg
public async Task<List<string>> MyAsyncMethod
returns a task that when completed will return a list of strings.