The await
keyword was added as part of C# 5.0 release which is supported from Visual Studio 2012 onwards. It leverages Task Parallel Library (TPL) which made the multi-threading relatively easier. The async
and await
keywords are used in pair in the same function as shown below. The await
keyword is used to pause the current asynchronous method's execution until the awaited asynchronous task is completed and/or its results returned. In order to use the await
keyword, the method that uses it must be marked with the async
keyword.
Using async
with void
is strongly discouraged. For more info you can look here.
Example:
public async Task DoSomethingAsync()
{
Console.WriteLine("Starting a useless process...");
Stopwatch stopwatch = Stopwatch.StartNew();
int delay = await UselessProcessAsync(1000);
stopwatch.Stop();
Console.WriteLine("A useless process took {0} milliseconds to execute.", stopwatch.ElapsedMilliseconds);
}
public async Task<int> UselessProcessAsync(int x)
{
await Task.Delay(x);
return x;
}
Output:
"Starting a useless process..."
**... 1 second delay... **"A useless process took 1000 milliseconds to execute."
The keyword pairs async
and await
can be omitted if a Task
or Task<T>
returning method only returns a single asynchronous operation.
Rather than this:
public async Task PrintAndDelayAsync(string message, int delay)
{
Debug.WriteLine(message);
await Task.Delay(x);
}
It is preferred to do this:
public Task PrintAndDelayAsync(string message, int delay)
{
Debug.WriteLine(message);
return Task.Delay(x);
}
In C# 5.0 await
cannot be used in catch
and finally
.
With C# 6.0 await
can be used in catch
and finally
.