Saturday, December 20, 2014

When to use void and Task as return type for Async method

As most of us are aware that there can be 3 return types of the method marked as Async.
  • Task
  • Task<T>
  • void
When any Async method has return type as void, it means not to return anything. In case of synchronous, this is fine. But situations become difficult when it comes to asynchronous operations.

While dealing with asynchronous operations, void behaves like ‘fire and forget’. It means whatever happens, but do not let caller know anything. So, it means, caller will not at all aware about the operation stage, whether it is successful or unsuccessful. As data type is void, method will not even propagate exceptions, which can be very harmful in some cases.

So, always use the word void with caution. If you don’t want your Async method to return anything, then also one should prefer to use return type as Task so that at least exceptions will be propagated to the caller.

No comments:

Post a Comment