Await Async in c#

      It is introduced in .net framework 4.5. async make the method asynchronous and await suspend the calling function and returns the control to the UI. There are two ways to implement async and await.

I/O bound

C#
private readonly HttpClient _httpClient = new HttpClient();

downloadButton.Clicked += async (o, e) =>
{
    // This line will yield control to the UI as the request
    // from the web service is happening.
    //
    // The UI thread is now free to perform other work.
    var stringData = await _httpClient.GetStringAsync(URL);
    DoSomethingWithData(stringData);
};

CPU bound

C#
private DamageResult CalculateDamageDone()
{
    // Code omitted:
    //
    // Does an expensive calculation and returns
    // the result of that calculation.
}


calculateButton.Clicked += async (o, e) =>
{
    // This line will yield control to the UI while CalculateDamageDone()
    // performs its work.  The UI thread is free to perform other work.
    var damageResult = await Task.Run(() => CalculateDamageDone());
    DisplayDamage(damageResult);
};

Key Pieces to Understand

  • Async code can be used for both I/O-bound and CPU-bound code, but differently for each scenario.
  • Async code uses Task<T> and Task, which are constructs used to model work being done in the background.
  • The async keyword turns a method into an async method, which allows you to use the await keyword in its body.
  • When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
  • await can only be used inside an async method.

Recognize CPU-Bound and I/O-Bound Work

Here are two questions you should ask before you write any code:
  1. Will your code be "waiting" for something, such as data from a database?
    If your answer is "yes", then your work is I/O-bound.
  2. Will your code be performing a very expensive computation?
    If you answered "yes", then your work is CPU-bound.
If the work you have is I/O-bound, use async and await without Task.Run. You should not use the Task Parallel Library. 
If the work you have is CPU-bound and you care about responsiveness, use asyncand await but spawn the work off on another thread with Task.Run

Comments

Popular posts from this blog

SQL Interview Questions and Answers

Generic Interface and Factory Pattern in C#

How to get device info IMEI programmatically in xamarin android