Saturday, 12 December 2015

How to set return values for methods returning Task<T>


Non-async method which returns Task<T>


If method is not marked as async and its return type is Task<T>, it has to return object of type Task<T> otherwise compiler issues an error. This is the example of the typical type mismatch error where code:


...causes a compiler error:

Error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task'

This can be rectified by simply returning expected type:



async method which returns Task<T>


If method is marked as async and its return type is Task<T>, it has to return object of type T, which is int in our case:


...but because async method lacks await in its body, this code generates compiler warning:

Warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

We can await only methods which return Task or Task<T> so this can be fixed by returning value from awaited completed task:


We have to be careful when calling methods returning Task<T>. If not await-ed, they return Task<T>. If awaited, they return object of Task's generic argument type, T. The following code is not awaiting method returning Task<int>:


...which causes compiler error:

Error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task'

Both methods are awaitable because they return object of type Task:


No comments: