Monday 20 January 2020

async await in C#

The async await comes in C# 5.0. This keywords is used in same function.
Suppose you have login task taht takes more time to response, it will stop the UI for this time.
So in this case you need to write asynchronous code.
The await keyword is used to stop the current method execution untill task is completed/ return result.
we can not use await if we not apply async keyword in function.

Note:1- async can not use with void, in this case Task Keyword is used in place of void.
for example:
 public async Task Hello()
{
}

Note:2- We should not use async, await when we have only single async operation
example:
// Bad
public async Task Hello(int x)
{  
   Console.WriteLine("hhh");
   await Task.Delay(x);
}
// Good
public Task PrintAndDelayAsync(int x)
 {
   Console.WriteLine("hhh"); 
   return Task.Delay(x);
 }
Note:3-  In C# 5.0 await keyword, MS cannot introduces in catch and finally
         In C# 6.0 and > await keyword, MS introduces in catch and finally

No comments:

Post a Comment