async/await in C#

async/await syntax should be used for I/O bound asynchronous operations only.

public async Task<int> GetUrlContentLengthAsync()
    var client = new HttpClient();

    Task<string> getStringTask =


    string contents = await getStringTask;

    return contents.Length;

Compiler transforms code into a state machine that to track yielding execution for await and resuming execution when a background job is finished.

Things to keep in mind:

  • async method needs await
  • add Async suffix to asynchronous methods
  • async void for ‘Fire and Forget’ work i.e. event Handlers
  • be aware of mixing LINQ with async lambdas
  • wait for tasks in a non-blocking manner (do not use Task.Result i.e.)
  • for tight loops use ValueTasks
  • Consider using ConfigureAwait(false) for performance and for avoiding deadlocks

Further read:

One Reply to “async/await in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
25 + 11 =