C# offers two key words
awaitto provide simplified asynchronous programming model in .net framework to easily write asynchronous code using concise syntax. It is based on Task based asynchronous pattern.
The core of async programming are
Task<T>objects, which model asynchronous operations. We can pattern Task based asynchronous code mostly for following two use cases
- For I/O bound code, you await an operation which returns a
Task<T>inside of an async method
- For CPU-bound code, you await an operation which usually runs on a background thread with the
The await keyboard is where magic happens. It yields control to the caller of the method that performed await, and it ultimately allows front end to be responsive and improves application performance.
awaitprinciples are not fully understood. A great deal of folks do not understand new pattern deeply resulting in a lousy asynchronous code.
There is certainly one basic rookie tip which can certainly improve your task based asynchronous code significantly. This tip is so simple yet very effective. It can help manage exception handling in asynchronous code in a better way.
Always return Task or Task<T> for Async methods. Avoid void for Async methods
Task return type always give calling code some kind of better handle over
Asyncmethod exceptions and state (completed, faulted) or lets calling code await
Asyncmethod. If you return
void, you lose all those benefits. Better get into habit of returning
Task<T>if there is a return value or simply return
TaskYou’ll be thankful to
Taskbecause it anchors exception from
Asyncmethod if it ever throws any exception or else it is lost in the space forever no clue why
Asyncmethod failed. Your Try-Catch block will never catch anything in case you chose to return
Code sample returns
Taskreturn type allows for better composing in calling code to check task status
public async Task PrintTemperature()
private async Task<double> GetTemperature()
Better Exception handling with Task
static void Main(string args)
catch (HttpRequestException ex) //exception caught from PrintTemperatureAsync
Console.WriteLine("Caught HttpRequestException", ex.Message);
catch (HttpRequestException ex) //exception never caught from PrintTemperatureAsync
Console.WriteLine("Never caught HttpRequestException", ex.Message);
public static async Task PrintTemperatureAsync()
///void return type
public static async void VoidPrintTemperatureAsync()
private static async Task<double> GetTemperatureAsync()
throw new HttpRequestException();
As shown below, calling code is able to catch exception from a
Task returning method whereas exception from a
void method goes unhandled and crashes the program.