When building applications with ASP.NET Core, performance and scalability are important considerations. An application may need to handle hundreds or thousands of requests while communicating with databases, external APIs, file systems, and other services.
If every operation blocks a thread while waiting for a response, the application can eventually run out of available threads to handle incoming requests.
This is where asynchronous programming becomes important.
C# provides the async and await keywords to make asynchronous programming easier to implement and understand. ASP.NET Core, Entity Framework Core, and many modern .NET libraries support asynchronous operations natively.
In this article, we'll explore how asynchronous programming works, why it matters, and how to use it correctly in real-world ASP.NET Core applications.
1. What Is Asynchronous Programming?
Asynchronous programming allows an operation to begin and then lets the calling code continue or return control while that operation is waiting to complete.
Consider an application retrieving data from a database.
In synchronous programming, the thread executing the database query remains occupied while waiting for the database response.
In asynchronous programming, the thread can return to the thread pool while the database operation is in progress. When the operation completes, the continuation of the method can execute using an available thread.
This is particularly useful for operations that spend significant time waiting for external resources.
Common examples include:
- Database queries
- HTTP requests to external APIs
- Reading and writing files
- Network communication
- Cloud storage operations
Asynchronous programming is primarily about improving resource utilization and application responsiveness, rather than making an individual operation execute faster.
2. Synchronous vs. Asynchronous Code
Synchronous Example
Consider a method that retrieves products from a database synchronously:
public List<Product> GetProducts()
{
return _context.Products.ToList();
}
When this method executes, the current thread waits until the database query finishes.
If the database takes two seconds to respond, the thread remains occupied during that waiting period.
Under high request traffic, many threads may spend their time waiting for database responses instead of handling other work.
Asynchronous Example
Now consider the asynchronous version:
public async Task<List<Product>> GetProductsAsync()
{
return await _context.Products.ToListAsync();
}
The ToListAsync() method executes the database operation asynchronously.
When the database operation is waiting for I/O, the application doesn't need to keep the request thread blocked for the entire duration.
This allows ASP.NET Core to make better use of available threads when handling concurrent requests.
3. Understanding async and await in C#
The async and await keywords work together to simplify asynchronous programming.
The async Keyword
The async keyword indicates that a method can use await and participate in asynchronous execution.
For example:
public async Task<string> GetMessageAsync()
{
await Task.Delay(1000);
return "Operation completed";
}
Here, Task.Delay(1000) simulates an asynchronous operation that takes one second.
The method returns a Task<string>, representing an operation that will eventually produce a string.
The await Keyword
The await keyword waits for an asynchronous operation to complete without blocking the current thread while that operation is waiting.
For example:
var message = await GetMessageAsync();
Execution continues after the awaited task completes.
The compiler manages the continuation of the method, allowing asynchronous code to be written in a readable, sequential style.
Understanding Task and Task<T>
C# provides two common task types.
Task
Represents an asynchronous operation that does not return a value.
public async Task SaveDataAsync()
{
await _context.SaveChangesAsync();
}
Task<T>
Represents an asynchronous operation that returns a value.
public async Task<Product?> GetProductAsync(int id)
{
return await _context.Products
.FirstOrDefaultAsync(p => p.Id == id);
}
The caller can await either type of task.
4. Implementing Async/Await in ASP.NET Core
Let's implement a practical example using an ASP.NET Core application with Entity Framework Core.
Assume we have a Product entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public bool IsActive { get; set; }
}
Step 1: Create an Asynchronous Service
Instead of performing database operations synchronously, create asynchronous methods.
using Microsoft.EntityFrameworkCore;
public class ProductService
{
private readonly ApplicationDbContext _context;
public ProductService(ApplicationDbContext context)
{
_context = context;
}
public async Task<List<Product>> GetAllProductsAsync()
{
return await _context.Products
.AsNoTracking()
.ToListAsync();
}
public async Task<Product?> GetProductByIdAsync(int id)
{
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id);
}
public async Task CreateProductAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
}
}
Entity Framework Core provides asynchronous methods such as:
ToListAsync()FirstOrDefaultAsync()SingleOrDefaultAsync()AnyAsync()CountAsync()SaveChangesAsync()AddAsync()
These methods are useful when database operations involve I/O.
Note that AddAsync() is not always necessary. For most entities, Add() is sufficient because adding an entity to the DbContext is generally an in-memory operation. AddAsync() exists primarily for scenarios involving asynchronous value generators.
Step 2: Use Async Methods in the Controller
Your ASP.NET Core controller can also use asynchronous methods.
public class ProductsController : Controller
{
private readonly ProductService _productService;
public ProductsController(ProductService productService)
{
_productService = productService;
}
public async Task<IActionResult> Index()
{
var products = await _productService
.GetAllProductsAsync();
return View(products);
}
public async Task<IActionResult> Details(int id)
{
var product = await _productService
.GetProductByIdAsync(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}
Notice that asynchronous programming continues throughout the application.
The controller awaits the service, and the service awaits the database operation.
This approach is often called async all the way.
Avoid converting an asynchronous operation back into synchronous execution unnecessarily.
5. Calling External APIs Asynchronously
Modern applications frequently communicate with external APIs.
For example, an application may retrieve exchange rates, payment information, shipping details, or third-party customer data.
Using HttpClient asynchronously is straightforward.
public class ExternalApiService
{
private readonly HttpClient _httpClient;
public ExternalApiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetDataAsync()
{
var response = await _httpClient.GetAsync(
"https://api.example.com/data");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
Both the HTTP request and reading the response content are asynchronous operations.
In ASP.NET Core, HttpClient should generally be managed through IHttpClientFactory rather than creating and disposing a new client for every request.
Registration:
builder.Services.AddHttpClient<ExternalApiService>();
This provides managed HttpClient instances and helps avoid common connection lifecycle and DNS-related issues associated with improper client management.
6. Running Multiple Operations Concurrently
Sometimes an application needs to perform multiple independent operations.
For example, a dashboard may need:
- Customer statistics
- Order statistics
- Revenue information
If these operations don't depend on each other, running them sequentially can unnecessarily increase response time.
Sequential Execution
var customers = await GetCustomersAsync(); var orders = await GetOrdersAsync(); var revenue = await GetRevenueAsync();
Each operation starts after the previous operation completes.
If each operation takes approximately one second, the total waiting time could be around three seconds.
Concurrent Execution with Task.WhenAll
var customersTask = GetCustomersAsync();
var ordersTask = GetOrdersAsync();
var revenueTask = GetRevenueAsync();
await Task.WhenAll(
customersTask,
ordersTask,
revenueTask);
var customers = await customersTask;
var orders = await ordersTask;
var revenue = await revenueTask;
The three operations are initiated before waiting for all of them to complete.
If they are truly independent and the underlying resources support concurrent operations, the total waiting time may be closer to the duration of the slowest operation rather than the sum of all three.
However, there is an important consideration when using Entity Framework Core.
A single DbContext does not support multiple concurrent operations.
This means you should not execute multiple database queries simultaneously using the same DbContext instance.
For example, this is problematic if all three methods use the same scoped DbContext:
var customersTask = _context.Customers.ToListAsync(); var ordersTask = _context.Orders.ToListAsync(); await Task.WhenAll(customersTask, ordersTask);
Instead, execute the operations sequentially using the same DbContext, or use separate DbContext instances when parallel database execution is genuinely necessary and properly managed.
Concurrency should be introduced carefully, not simply because Task.WhenAll() is available.
7. Using CancellationToken
In ASP.NET Core, requests may be cancelled when the client disconnects, when a timeout occurs, or when the application no longer needs to complete the operation.
Passing a CancellationToken allows asynchronous operations to respond to cancellation requests.
Example:
public async Task<List<Product>> GetProductsAsync(
CancellationToken cancellationToken)
{
return await _context.Products
.AsNoTracking()
.ToListAsync(cancellationToken);
}
In the controller:
public async Task<IActionResult> Index(
CancellationToken cancellationToken)
{
var products = await _context.Products
.AsNoTracking()
.ToListAsync(cancellationToken);
return View(products);
}
ASP.NET Core can provide the request cancellation token through the action parameter.
Passing it to database queries and external API requests helps avoid continuing unnecessary work after a request has been cancelled.
For example, an HTTP request can also accept a cancellation token:
public async Task<string> GetDataAsync(
CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(
"https://api.example.com/data",
cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(
cancellationToken);
}
Cancellation is especially useful for long-running requests, report generation, API integrations, and database queries.
8. Common Async/Await Mistakes
Asynchronous programming is easy to implement, but there are several mistakes developers should avoid.
Mistake 1: Using .Result or .Wait()
Avoid blocking asynchronous operations:
var products = GetProductsAsync().Result;
Or:
GetProductsAsync().Wait();
These approaches block the current thread while waiting for the task to complete.
They can reduce scalability and may contribute to deadlocks in certain environments or execution contexts.
Prefer:
var products = await GetProductsAsync();
Mistake 2: Using async Without Await
This method provides no meaningful asynchronous behavior:
public async Task<int> GetNumberAsync()
{
return 10;
}
There is no asynchronous operation being awaited.
If a method simply returns a value, it should generally be synchronous:
public int GetNumber()
{
return 10;
}
If a method needs to return a completed task for an asynchronous interface, it can use:
public Task<int> GetNumberAsync()
{
return Task.FromResult(10);
}
Mistake 3: Using Task.Run for Database Calls
A common misconception is that wrapping every operation inside Task.Run() makes it asynchronous.
For example:
var products = await Task.Run(() =>
_context.Products.ToList());
This moves synchronous database work onto another thread, but it does not turn the database operation into true asynchronous I/O.
It still consumes a thread while the database operation is waiting.
For ASP.NET Core web applications, prefer the asynchronous methods already provided by Entity Framework Core:
var products = await _context.Products.ToListAsync();
Task.Run() is more appropriate for CPU-bound work in scenarios where moving the computation to another thread is beneficial, and even then, it should be used carefully in server applications.
Mistake 4: Making Every Method Asynchronous
Not every method needs to be asynchronous.
Simple calculations, string manipulation, in-memory operations, and ordinary property access usually don't benefit from async and await.
For example:
public decimal CalculateTotal(
decimal price,
int quantity)
{
return price * quantity;
}
There is no reason to convert this method into an asynchronous method.
Use asynchronous programming where operations involve waiting for I/O or where an asynchronous contract is required.
Mistake 5: Ignoring Exceptions
Asynchronous operations can throw exceptions just like synchronous methods.
For example:
try
{
var products = await _productService
.GetProductsAsync();
}
catch (Exception ex)
{
// Log the exception
}
In real applications, exception handling should generally be implemented using centralized exception-handling middleware rather than repeating broad exception handling throughout every controller.
Always ensure that failures from asynchronous operations are properly handled and logged.
9. Does Async/Await Make Your Application Faster?
This is an important distinction.
Asynchronous programming does not necessarily make an individual database query, API request, or file operation complete faster.
If a database query takes 500 milliseconds, using await does not automatically reduce it to 100 milliseconds.
The primary benefit is that the application can avoid blocking threads while waiting for I/O operations to complete.
This improves resource utilization and can help an ASP.NET Core application handle more concurrent requests under appropriate workloads.
However, performance still depends on several factors:
- Database query efficiency
- Indexing
- Network latency
- Application architecture
- Available resources
- Connection pool capacity
- Thread pool behavior
- External service performance
Asynchronous programming is an important part of building scalable applications, but it is not a substitute for proper performance optimization.
10. Best Practices for Async/Await in ASP.NET Core
When working with asynchronous programming in .NET, follow these practical guidelines:
- Use async methods for I/O-bound operations such as database queries, HTTP requests, and file operations.
- Use
awaitinstead of blocking with.Resultor.Wait(). - Follow the async-all-the-way approach through controllers, services, and data access.
- Use asynchronous Entity Framework Core methods for database operations.
- Pass
CancellationTokenthrough long-running operations. - Use
Task.WhenAll()only when operations are independent and safe to execute concurrently. - Avoid unnecessary
Task.Run()in ASP.NET Core request handlers. - Don't make simple in-memory methods asynchronous without a reason.
- Use
IHttpClientFactoryfor managing HTTP clients. - Measure performance instead of assuming asynchronous code automatically makes everything faster.
Conclusion
Asynchronous programming is an essential skill for modern C# and ASP.NET Core development.
The async and await keywords make it easier to write non-blocking code that is readable and maintainable. When used with database operations, external APIs, file processing, and other I/O-bound workloads, asynchronous programming helps applications use resources more efficiently and handle concurrent requests more effectively.
However, async/await should not be applied blindly. Understanding when to use it, how tasks work, how cancellation is handled, and when concurrency is appropriate is what makes the difference between good asynchronous code and unnecessary complexity.
As you build larger ASP.NET Core applications, adopting the async-all-the-way approach for I/O-bound operations will help you create applications that are more scalable, responsive, and production-ready.