Search Sreeni's Insights

Filter by content type
crafting July 21, 2015 7 min read

Async and await in C# - common mistakes

Async and await explained for web applications, including I/O-bound work, async void, blocking calls, deadlocks, ConfigureAwait, fake async, and sequential awaits.

Share:

Async and await in C# - common mistakes

Most of the modern web applications are spending their time waiting, waiting for the database, waiting for a web service, waiting for a file to be read. With async and await (introduced in C# 5 and .NET 4.5), writing asynchronous code is almost as easy as writing synchronous code. But “almost” is the key word here. Small mistakes like async void or calling .Result can crash the application or freeze it with a deadlock, and these issues usually appear only under load in production. In this article, we are going to see why we need async, how it works in simple terms and the common mistakes with their fixes.

TL;DR Summary

  • Async frees the thread while waiting for I/O, so the server can handle more requests with the same threads.
  • Async is for I/O-bound work, not for CPU-bound work in ASP.NET.
  • Don’t use async void, except for event handlers. Use async Task.
  • Don’t block on async code with .Result or .Wait(), it can deadlock in ASP.NET and UI applications.
  • Go “async all the way”, from the controller to the database call.
  • Use ConfigureAwait(false) in library code.
  • Don’t wrap synchronous code with Task.Run in ASP.NET just to make it look async.

Challenges

Thread pool starvation

In ASP.NET, every request uses a thread from the thread pool. When the request is waiting for a slow database or web service call synchronously, the thread is blocked and doing nothing. Under load, all threads are blocked, new requests are queued and the response time is going up, sometimes the users get HTTP 503 errors. The server CPU is low, but the application is not responding.

Deadlocks that appear only in production

Mixing synchronous and asynchronous code with .Result works fine in a console application or unit tests, but deadlocks in ASP.NET or WPF. The page just hangs forever. It is very hard to diagnose, because there is no exception, nothing in the logs.

Crashes from async void

An exception thrown inside an async void method cannot be caught by the caller. In ASP.NET, it can crash the whole process. Again, it is very hard to find the root cause.

What is async and await?

async and await are C# keywords which allow us to write asynchronous code in a sequential style. The async modifier marks a method as asynchronous and await suspends the method until the awaited task completes, without blocking the thread.

In simple terms, when the code hits await, it says “I am waiting for this, the thread can go and do other work, call me back when the result is ready”.

Think about ordering food in a restaurant. A synchronous waiter takes your order, goes to the kitchen and stands there until the food is ready, and all other tables are waiting. An asynchronous waiter gives the order to the kitchen and serves other tables in the meantime. When the food is ready, he (or another waiter) brings it to you. Same number of waiters, many more customers served.

public async Task<ActionResult> Details(int id)
{
    var fund = await _db.Funds.FindAsync(id);
    return View(fund);
}

While FindAsync is waiting for SQL Server, the thread goes back to the pool and serves other requests.

Why async is important?

In order to handle more requests with the same server resources, to keep the UI responsive and to avoid thread pool starvation under load, we should use async for all I/O-bound operations, i.e. database calls, HTTP calls, file and blob storage access. ASP.NET MVC 5, Web API 2, Entity Framework 6 (ToListAsync, SaveChangesAsync), HttpClient and Azure Storage SDK all support async out of the box.

Keep in mind that async doesn’t make a single request faster. It makes the server scale better under load.

Common Mistakes

Let us discuss the common mistakes one by one with the fix.

Mistake 1: async void

// Bad
public async void SaveAuditLog(string message)
{
    await _auditRepository.InsertAsync(message);
}

The caller cannot await it, cannot know when it is finished and cannot catch its exceptions. When InsertAsync throws, the exception is raised directly on the synchronization context and in ASP.NET it can bring down the process.

// Good
public async Task SaveAuditLogAsync(string message)
{
    await _auditRepository.InsertAsync(message);
}

Note: async void is only allowed for event handlers, i.e. private async void SaveButton_Click(object sender, EventArgs e), because the event handler signature requires void. Even there, wrap the body with try-catch.

Mistake 2: Blocking with .Result or .Wait() (deadlock)

// Bad
public ActionResult Index()
{
    var funds = _fundService.GetFundsAsync().Result;
    return View(funds);
}

public async Task<List<Fund>> GetFundsAsync()
{
    var json = await _httpClient.GetStringAsync("api/funds");
    return JsonConvert.DeserializeObject<List<Fund>>(json);
}

Here is what happens in ASP.NET,

  1. Index calls GetFundsAsync and blocks the request thread on .Result.
  2. GetFundsAsync awaits the HTTP call. By default, await captures the ASP.NET synchronization context, so the continuation wants to resume on the same request context.
  3. The HTTP call completes, the continuation tries to enter the request context, but the context is held by the thread blocked on .Result.
  4. Each one is waiting for the other. Deadlock.

The fix is to go async all the way.

// Good
public async Task<ActionResult> Index()
{
    var funds = await _fundService.GetFundsAsync();
    return View(funds);
}

Mistake 3: Not going async all the way

Making only the lowest method async and blocking somewhere in the middle gives all the problems of async and none of the benefits. Async is contagious, once one method is async, its callers should be async too, up to the controller action. Plan it from the top.

Mistake 4: Forgetting ConfigureAwait(false) in library code

Library code (repositories, service clients, shared libraries) doesn’t need the ASP.NET request context to continue. Use ConfigureAwait(false), so that the continuation can run on any thread pool thread. It gives slightly better performance and protects against the deadlock if some caller is still blocking.

public async Task<List<Fund>> GetFundsAsync()
{
    var json = await _httpClient.GetStringAsync("api/funds").ConfigureAwait(false);
    return JsonConvert.DeserializeObject<List<Fund>>(json);
}

Note: Don’t use ConfigureAwait(false) in the controller action itself, if the code after await needs HttpContext.Current, the culture or the user principal. In ASP.NET MVC, those come from the request context.

Mistake 5: Fake async with Task.Run in ASP.NET

// Bad
public Task<decimal> CalculateNavAsync(Fund fund)
{
    return Task.Run(() => CalculateNav(fund));
}

In ASP.NET, Task.Run just moves the work from one thread pool thread to another thread pool thread. It adds overhead and doesn’t free any thread. For CPU-bound work in ASP.NET, keep it synchronous. Task.Run is useful in desktop UI applications to keep the UI thread responsive, not on the server.

Mistake 6: Awaiting in a loop when calls are independent

// Slow - one after another
foreach (var fundId in fundIds)
{
    prices.Add(await _pricingClient.GetPriceAsync(fundId));
}

// Faster - all in parallel
var tasks = fundIds.Select(id => _pricingClient.GetPriceAsync(id));
var prices = await Task.WhenAll(tasks);

Be mindful not to fire hundreds of parallel calls to a downstream service, otherwise you will overload it. Batch them if the list is large.

Info: Don’t run parallel queries on the same Entity Framework DbContext. DbContext is not thread-safe and EF6 throws an exception when a second async operation is started before the first one is completed.

Mistake 7: Not using the Async suffix and returning null Task

  • Name the async methods with Async suffix (ex: GetFundsAsync), so the caller knows to await it.
  • Never return null from a method which returns Task. Awaiting null throws NullReferenceException. Return Task.FromResult(value) for already available results (and Task.CompletedTask when you are on .NET 4.6).

Quick Summary

Find below the quick summary of the do’s and don’ts,

Don’tDo
async voidasync Task
.Result, .Wait()await
Async only at the bottomAsync all the way to the controller
await without thinking in librariesConfigureAwait(false) in libraries
Task.Run for CPU work in ASP.NETKeep CPU work synchronous on the server
await in a loop for independent callsTask.WhenAll
Return null for TaskTask.FromResult(...)

Wrap up

In this article, we have looked at why we need async in web applications, how async and await work in simple terms and the common mistakes like async void, .Result deadlocks, missing ConfigureAwait(false), fake async with Task.Run and sequential awaits. Thanks for reading this article. I hope this article provided you some insights into async and await in C#. In the next article, I will walk you through how to deploy an ASP.NET MVC application to Azure App Service.

Related Posts