Sub topic 9
Using Async Methods
In earlier chapters you called methods like ToListAsync and SaveChangesAsync. This chapter explains what the word "Async" means, why EF Core offers these methods, and how to use them without making common mistakes.
What "async" means
A database call takes time. The request goes over a network or to a disk, the database does its work, and the result comes back. That can take a few milliseconds or several seconds.
A thread is a worker inside your program that runs your code. With a synchronous call, the thread waits and does nothing else until the database answers. This is called blocking.
An asynchronous call (async for short) starts the database work and then lets the thread go off and do other jobs. When the answer arrives, your code picks up where it stopped.
Here is an everyday comparison. You order coffee. In the synchronous version, you stand at the counter until it is ready. In the asynchronous version, you get a buzzer, sit down, and answer emails. When the buzzer goes off, you collect your coffee.
Why it matters
In a small console app, async makes little difference. Only one person is using it.
A web server is different. It handles many users at once, and each request needs a thread. If every thread is stuck waiting on the database, new requests have to queue. Async frees those threads while they wait, so the same server can handle more users.
The two keywords: Task and await
C# uses two pieces for async code:
- A Task is an object that stands for work that will finish later.
Task<List<Blog>>means "a list of blogs, coming soon." - The await keyword pauses your method until the task finishes, without blocking the thread. It then gives you the result.
A method that uses await must be marked async and usually returns Task or Task<T>.
public static async Task<int> CountBlogsAsync(BloggingContext db)
{
return await db.Blogs.CountAsync();
}By convention, method names that return a task end in Async.
How an async query flows
The async methods you will use most
EF Core has an async version of each method that runs a query or saves data. These methods are extension methods, which are methods added to a type from another class. They live in the Microsoft.EntityFrameworkCore namespace, so you need that using line at the top of your file.
| Synchronous | Asynchronous | What it does |
|---|---|---|
| `ToList()` | `ToListAsync()` | Returns all matching rows as a list |
| `First()` | `FirstAsync()` | Returns the first row, throws if there are none |
| `FirstOrDefault()` | `FirstOrDefaultAsync()` | Returns the first row, or `null` |
| `SingleOrDefault()` | `SingleOrDefaultAsync()` | Returns the only row, or `null`, and throws if there are more than one |
| `Find()` | `FindAsync()` | Looks up a row by primary key |
| `Count()` | `CountAsync()` | Counts matching rows |
| `Any()` | `AnyAsync()` | Checks whether any row matches |
| `SaveChanges()` | `SaveChangesAsync()` | Writes changes to the database |
Methods like Where, OrderBy, and Select have no async version. They only build the query and do not touch the database. The database is contacted only at the final step, such as ToListAsync.
A complete worked example
This program uses the Blog, Post, and BloggingContext classes and the migrated blogging.db database from earlier chapters. Put it in Program.cs. Top-level statements allow await directly, with no Main method needed.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
// Add a blog only if none exists yet
bool hasBlogs = await db.Blogs.AnyAsync();
if (!hasBlogs)
{
db.Blogs.Add(new Blog { Url = "https://example.com/async" });
await db.SaveChangesAsync();
}
// Count and list blogs
int count = await db.Blogs.CountAsync();
Console.WriteLine($"There are {count} blog(s).");
List<Blog> blogs = await db.Blogs
.OrderBy(b => b.Url)
.ToListAsync();
foreach (var blog in blogs)
{
Console.WriteLine($"{blog.BlogId}: {blog.Url}");
}
// Look up one blog by key
Blog? first = await db.Blogs.FindAsync(blogs[0].BlogId);
Console.WriteLine($"Found: {first?.Url}");Run it with dotnet run. Every database call is awaited, one after another.
Cancelling slow work
Sometimes you want to give up on a slow query. Maybe a user closed the web page. Most async methods accept a CancellationToken, which is a signal that says "stop now."
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
var blogs = await db.Blogs.ToListAsync(cts.Token);
Console.WriteLine($"Loaded {blogs.Count} blogs.");
}
catch (OperationCanceledException)
{
Console.WriteLine("The query took too long and was cancelled.");
}In ASP.NET Core, the framework gives each request a token that fires when the client disconnects. Later, in the dependency injection chapter, you will see endpoints you can pass that token to.
Common mistakes
Forgetting await
If you leave out await, you get a Task, not your data. Worse, SaveChangesAsync() without await may not finish before your code moves on or the context is disposed. The compiler usually warns you (warning CS4014). Read that warning.
Blocking with .Result or .Wait()
Writing db.Blogs.ToListAsync().Result blocks the thread, which throws away the benefit of async. In some apps it can even freeze the program in a deadlock, where two pieces of code each wait for the other forever. Use await throughout. If you cannot use await somewhere, call the synchronous method instead.
Running two operations at once on one context
A DbContext can only do one thing at a time. This code fails:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blogsTask = db.Blogs.ToListAsync();
var postsTask = db.Posts.ToListAsync(); // second operation starts too early
await Task.WhenAll(blogsTask, postsTask); // throws InvalidOperationExceptionThe error says "A second operation was started on this context instance before a previous operation completed." The fix is simple: await each call before starting the next one. If you really need parallel queries, give each one its own DbContext.
Mixing sync and async for no reason
Pick one style per code path. In web apps, use async for all database calls. In a small script, sync is acceptable, but staying consistent is easier to read.
Summary
- Async methods free the thread while the database works. This helps web apps serve more users.
- Await every async call, and add
using Microsoft.EntityFrameworkCore;. - Only the methods that run the query or save data are async. Methods that build the query, like
Where, are not. - Pass a
CancellationTokenwhen work might need to stop early. - Never run two operations at once on the same context.
Exercise
A teammate writes var count = db.Blogs.CountAsync(); and then Console.WriteLine(count);. The output is not a number. What went wrong, and how do you fix it?
Show answer
Without await, CountAsync() returns a Task<int> instead of the number, so the program prints the task object. Write var count = await db.Blogs.CountAsync(); inside an async method or in top-level statements.
Exercise
Why is there no WhereAsync method in EF Core?
Show answer
Where only adds a filter to the query being built and never contacts the database. Only methods that run the query, such as ToListAsync, FirstAsync, or CountAsync, do I/O and need async versions.
Exercise
You start db.Blogs.ToListAsync() and db.Posts.ToListAsync() on the same context without awaiting the first one, and then call Task.WhenAll. What happens, and what are two ways to fix it?
Show answer
EF Core throws an InvalidOperationException because a DbContext allows only one operation at a time. One fix is to await each query in turn. The other is to give each query its own DbContext instance so they can run in parallel.