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:


1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : (
atmmachinehackers1@gmail.com ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;
atmmachinehackers1@gmail.com