Home Return Type of an Immediate await vs Postponed await
Reply: 1

Return Type of an Immediate await vs Postponed await

8protons
1#
8protons Published in 2017-12-07 23:39:55Z

I am seeking clarification as to why an immediate await returns the type of the asynchronous, non-void task whereas postponing the await returns the task itself. If my terminology in the title or elsewhere is incorrect, please let me know.

private async Task<string> GetUserId(Guid id)
{
   string thisUserId = null;
   ... do stuff ...
   return thisUserId;
}

public async Task<IActionResult> MyFunc(Guid id)
{
   var a = await GetUserId(id);
   var b = GetUserId(id);
   ... do stuff ...
   await b;

   return Ok(true);
}

Why is a of type string while b is of type Task<string>?

krillgar
2#
krillgar Reply to 2017-12-07 23:45:43Z

In both cases, your method is always returning an object of type Task<string>. However, when you perform the await, the result of that is the result of the Task, which is your string.

So, if you do that when you originally call the method, you're processing the Task immediately. However with your second call, you don't process the Task until after you "do stuff". In that case, your variable is still the Task that will return the string. Once you finally call await on it, then you get the result of that task.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323151 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO