Async actions with async and await
Most actions wait on a database, a file or another web service. Writing them with async and await lets the server handle far more requests with the same hardware. This lesson shows how to write async actions correctly and the mistakes that cancel out the benefit.
- StartRequest arrivesThread from the pool starts the action
- Step 2await database callThread goes back to the pool
- Step 3Other requests servedSame thread helps someone else
- Step 4Data returnsA pool thread continues the action
- EndView renderedResponse sent
Why async
ASP.NET Core serves requests from a pool of threads. A synchronous action that waits 200 ms for SQL holds its thread the whole time. With await, the thread returns to the pool during the wait and serves other requests. Under load this is the difference between a responsive site and one that queues requests.
Async does not make one request faster; it lets the server handle many more at the same time.
Writing an async action
Mark the action async, return Task<IActionResult>, and await every I/O call. Accept a CancellationToken; ASP.NET Core passes one that is cancelled when the user closes the page.
public class WeatherController(ShopContext db, HttpClient http) : Controller
{
public async Task<IActionResult> Index(string city, CancellationToken ct)
{
var favourites = await db.Cities
.Where(c => c.IsFavourite)
.ToListAsync(ct);
var forecast = await http.GetFromJsonAsync<Forecast>($"forecast?city={Uri.EscapeDataString(city)}", ct);
return View(new WeatherPage(favourites, forecast));
}
}Running independent calls together
When two calls do not depend on each other and do not share a DbContext, start both and await them together.
var weatherTask = weatherClient.GetAsync(city, ct);
var newsTask = newsClient.GetLatestAsync(ct);
await Task.WhenAll(weatherTask, newsTask);
return View(new HomePage(weatherTask.Result, newsTask.Result)); // already completed, safeMistakes to avoid
- .Result or .Wait() on an unfinished task blocks a thread and can cause thread-pool starvation.
- async void methods cannot be awaited and crash the process on errors; use async Task.
- Mixing sync I/O (File.ReadAllText, ToList) into async actions loses the benefit.
- Two parallel queries on the same DbContext throw an error; run them one after the other.
- Task.Run inside an action just moves the work to another pool thread; it does not help.
Interview question
Does making a controller action async make it faster?
Not for a single request: the work still takes as long. Async releases the thread while the action waits on I/O such as a database or HTTP call, so the server can handle many more concurrent requests with the same threads. The benefit appears under load as higher throughput and fewer queued requests.
Want the full details? Read the official Microsoft documentation for this topic.