Sub topic 9
Using Async Methods
Your program has to wait every time it talks to the database. A query might take a few milliseconds or a few seconds. EF Core gives you async methods so your program can do other useful work while it waits.
What "async" means
An asynchronous (async) method is a method that starts some work and returns right away, without blocking. It hands back a Task. A Task is an object that stands for work that will finish later.
The await keyword tells C# to pause this method until the Task finishes. While it is paused, the thread (the worker that runs your code) is free to do other jobs. In a web app, that free thread can serve another user's request.
In EF Core, async methods end in Async. Here are the common pairs:
| Sync method | Async method |
|---|---|
| `ToList()` | `ToListAsync()` |
| `First()` | `FirstAsync()` |
| `FirstOrDefault()` | `FirstOrDefaultAsync()` |
| `Count()` | `CountAsync()` |
| `SaveChanges()` | `SaveChangesAsync()` |
A worked example
This program uses the Blog, Post, and BloggingContext classes from earlier chapters. Put it in Program.cs. A console app with top-level statements can use await directly.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
db.Blogs.Add(new Blog { Url = "https://example.com/async" });
int saved = await db.SaveChangesAsync();
Console.WriteLine($"Rows saved: {saved}");
int count = await db.Blogs.CountAsync();
Console.WriteLine($"Blogs in database: {count}");
var blog = await db.Blogs
.Where(b => b.Url.Contains("async"))
.FirstOrDefaultAsync();
Console.WriteLine(blog?.Url ?? "Not found");
List<Blog> all = await db.Blogs.OrderBy(b => b.BlogId).ToListAsync();
foreach (var b in all)
{
Console.WriteLine($"{b.BlogId}: {b.Url}");
}Run it with dotnet run. Note that Where and OrderBy have no async version. They only build the query. The query runs when you call a method like ToListAsync, so only that call needs await.
Common mistakes
- Forgetting
await. If you writedb.SaveChangesAsync();with noawait, your code moves on before the save finishes. You may then read stale data, or the context may be disposed while it is still saving. - Running two operations at once on one context. A
DbContexthandles only one operation at a time. Start a query,awaitit, then start the next. Don't start both and await them together. - Blocking with
.Resultor.Wait(). These calls make the thread wait, which cancels the benefit of async. In some apps they can even freeze the program. Useawaitinstead.
Exercise
This line compiles but does not behave as intended: var blogs = db.Blogs.ToListAsync();. What type does blogs have, and how do you fix it?
Show answer
blogs is a Task<List<Blog>>, not a list. The query may not have finished yet. Add await: var blogs = await db.Blogs.ToListAsync(); so blogs becomes a List<Blog>.
Exercise
Which call in await db.Blogs.Where(b => b.BlogId > 1).OrderBy(b => b.Url).CountAsync(); actually sends SQL to the database?
Show answer
CountAsync(). Where and OrderBy only build the query. CountAsync runs it and returns a Task, which you await.