In modern web backends and microservices, threads are a finite operating system resource. Using blocking operations (Thread.Sleep, .Result, .Wait()) consumes OS threads while they sit idle waiting for network or disk I/O, leading to thread pool starvation and server crashes under load.
1. How async and await Function Under the Hood
When an asynchronous method reaches an await statement on an incomplete task:
- The method yields execution back to the caller.
- The current thread is returned to the .NET ThreadPool to serve other incoming HTTP requests.
- When the I/O operation finishes (e.g. database returns rows, network packet arrives), the OS notifies the runtime via an I/O Completion Port (IOCP).
- The ThreadPool assigns an available worker thread to resume execution of the method state machine.
public class UserService
{
private readonly HttpClient _httpClient;
public UserService(HttpClient httpClient)
{
_httpClient = httpClient;
}
// Always suffix async methods with 'Async' and accept a CancellationToken
public async Task<UserDto?> FetchUserProfileAsync(Guid userId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync(
$"https://api.codeacademix.dev/users/{userId}",
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<UserDto>(cancellationToken: cancellationToken);
}
}
2. Task vs ValueTask
Task/Task<T>: An object allocated on the managed heap. Use for general asynchronous operations where waiting for I/O is guaranteed.ValueTask/ValueTask<T>: A stack-allocated struct. Use when an asynchronous method frequently completes synchronously (e.g. reading from an in-memory cache), saving thousands of heap allocations per second.
public class CacheService
{
private readonly Dictionary<string, string> _memoryCache = new();
public ValueTask<string?> GetCachedValueAsync(string key)
{
// Completes synchronously without allocating a Task on the heap!
if (_memoryCache.TryGetValue(key, out var cachedValue))
{
return ValueTask.FromResult<string?>(cachedValue);
}
// Falls back to asynchronous database fetch
return new ValueTask<string?>(FetchFromDbAsync(key));
}
private async Task<string?> FetchFromDbAsync(string key)
{
await Task.Delay(100); // Simulated DB query
return "data";
}
}
3. The 3 Golden Rules of Async in .NET
- Never use
.Resultor.Wait(): This blocks the thread synchronously and frequently causes deadlocks. Useawaitall the way up. - Always accept and propagate
CancellationToken: When a web browser cancels an HTTP request, propagating the token cancels long-running database queries instantly, saving CPU. - Avoid
async void: Always returnTaskorValueTask. The only valid exception forasync voidis UI event handlers (e.g., button click).