4. C# tip – Always return Task or Task <T> for Async methods

By | November 29, 2017
C# offers two key words Async and await to 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 and 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 or Task<T> inside of an async method
  • For CPU-bound code, you await an operation which usually runs on a background thread with the Task.Run method
 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.
However, Async/await principles 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 Async method exceptions and state (completed, faulted) or lets calling code  await Async method. 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 Task You’ll be thankful to Task because it anchors exception from Async method if it ever throws any exception or else it is lost in the space forever no clue why Async method failed. Your Try-Catch block will never catch anything in case you chose to return void
Code sample returns Task though PrintTemperature returns nothing. Task return type allows for better composing in calling code to check task status

Better Exception handling with Task

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.

Leave a Reply

Your email address will not be published. Required fields are marked *