Concurrency in .NET: async/await, Tasks, Parallel and Thread Safety

Concurrency in .NET covers several different tools that are easy to mix up: async/await for waiting on I/O, Task.WhenAll for running independent operations together, Parallel for CPU-bound work, and locks, SemaphoreSlim and concurrent collections for protecting shared state. Using the wrong one is a common source of slow or deadlocked applications.
This guide explains each tool with a small, runnable example and shows which one to pick.
Concurrency vs parallelism
- Concurrency means making progress on several things during the same period of time. A web server handling thousands of requests while most of them wait for the database is concurrent.
- Parallelism means literally running work at the same time on multiple CPU cores. Resizing 1,000 images on an 8-core machine is parallel.
In .NET, async/await mostly gives you concurrency for I/O-bound work, and Parallel/PLINQ give you parallelism for CPU-bound work.
async and await for I/O
When code awaits an I/O operation (HTTP call, database query, file read), the thread is released back to the thread pool instead of sitting idle. This is what lets ASP.NET Core serve many requests with few threads.
public async Task<Customer?> GetCustomerAsync(int id, CancellationToken ct)
{
await using var conn = new NpgsqlConnection(_connectionString);
await conn.OpenAsync(ct);
return await conn.QuerySingleOrDefaultAsync<Customer>(
new CommandDefinition("SELECT * FROM customers WHERE id = @id", new { id }, cancellationToken: ct));
}
Three rules cover most cases:
- Async all the way. Do not block on async code with
.Resultor.Wait(). In apps with a synchronization context (WinForms, WPF, old ASP.NET) this can deadlock; everywhere else it wastes a thread. - **Pass a
CancellationToken** through every async method, so work stops when the request is aborted. - **Avoid
async void** except for event handlers. Exceptions inasync voidmethods cannot be caught by the caller and can crash the process.
Running independent operations together with Task.WhenAll
Awaiting calls one after another makes the total time the sum of all calls:
// Sequential: ~300 ms if each call takes ~100 ms
var user = await api.GetUserAsync(id, ct);
var orders = await api.GetOrdersAsync(id, ct);
var credits = await api.GetCreditsAsync(id, ct);
If the calls do not depend on each other, start them all first and await them together:
// Concurrent: ~100 ms
var userTask = api.GetUserAsync(id, ct);
var ordersTask = api.GetOrdersAsync(id, ct);
var creditsTask = api.GetCreditsAsync(id, ct);
await Task.WhenAll(userTask, ordersTask, creditsTask);
var dashboard = new Dashboard(userTask.Result, ordersTask.Result, creditsTask.Result);
Reading .Result here is safe because the tasks have already completed.
One caveat: a single DbContext or database connection must not be used by two operations at the same time. Run concurrent queries on separate contexts or connections.
Limiting concurrency with Parallel.ForEachAsync
Starting 10,000 HTTP requests at once with Task.WhenAll can exhaust sockets or get you rate-limited. Parallel.ForEachAsync (available since .NET 6) processes items concurrently with a limit:
var options = new ParallelOptions { MaxDegreeOfParallelism = 8, CancellationToken = ct };
await Parallel.ForEachAsync(productIds, options, async (id, token) =>
{
var price = await priceApi.GetPriceAsync(id, token);
await cache.SetAsync(id, price, token);
});
An alternative for more control is SemaphoreSlim (shown below).
CPU-bound work with Parallel and PLINQ
For work that keeps the CPU busy, such as image processing, hashing or calculations, use Parallel.For/Parallel.ForEach or PLINQ:
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, file =>
{
var thumbnail = ImageResizer.Resize(File.ReadAllBytes(file), 320, 240);
File.WriteAllBytes(Path.ChangeExtension(file, ".thumb.jpg"), thumbnail);
});
var total = orders.AsParallel().Where(o => o.IsPaid).Sum(o => o.CalculateTax());
Do not use Parallel.ForEach with async lambdas: it does not await them, so the loop finishes before the work does. Use Parallel.ForEachAsync for async work.
In an ASP.NET Core request, wrapping synchronous work in Task.Run does not make it faster; it only moves it to another thread-pool thread. Task.Run is useful in UI apps to keep the UI thread responsive, or to offload a genuinely CPU-heavy job.
Protecting shared state
When multiple threads read and write the same data, you need synchronization. This counter is broken:
int count = 0;
Parallel.For(0, 100_000, _ => count++); // result is usually less than 100000
Console.WriteLine(count);
count++ is a read, an add and a write; two threads can read the same value and both write back the same result. Fixes, from lightest to heaviest:
Interlocked for single numeric operations:
Parallel.For(0, 100_000, _ => Interlocked.Increment(ref count));
lock for protecting a block of code (synchronous only):
private readonly Lock _gate = new(); // .NET 9+; use `new object()` on older versions
private readonly List<string> _log = new();
public void Add(string message)
{
lock (_gate)
{
_log.Add(message);
}
}
SemaphoreSlim when the protected section contains await. You cannot await inside a lock block, but you can with a semaphore:
private readonly SemaphoreSlim _refreshGate = new(1, 1);
public async Task<string> GetTokenAsync(CancellationToken ct)
{
if (!_token.IsExpired) return _token.Value;
await _refreshGate.WaitAsync(ct);
try
{
if (_token.IsExpired) // check again: another caller may have refreshed it
_token = await _auth.RefreshAsync(ct);
return _token.Value;
}
finally
{
_refreshGate.Release();
}
}
new SemaphoreSlim(8, 8) works as a throttle, allowing up to eight callers in at once.
Concurrent collections avoid manual locking for common data structures:
var cache = new ConcurrentDictionary<int, Product>();
var product = cache.GetOrAdd(id, key => LoadProduct(key));
Note that the factory passed to GetOrAdd may run more than once under contention; only one result is stored. If the factory is expensive, store a Lazy<T> instead.
Producer/consumer with Channels
System.Threading.Channels is the modern way to pass work between producers and consumers, for example a background queue in an ASP.NET Core app:
var channel = Channel.CreateBounded<Order>(new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.Wait,
});
// Producer
await channel.Writer.WriteAsync(order, ct);
// Consumer (e.g. in a BackgroundService)
await foreach (var o in channel.Reader.ReadAllAsync(ct))
{
await ProcessAsync(o, ct);
}
A bounded channel applies back-pressure: when the queue is full, producers wait instead of using unlimited memory.
Which tool should I use?
| Situation | Use |
|---|---|
| Waiting on HTTP, database, files | async/await |
| Several independent I/O calls | Task.WhenAll |
| Many I/O calls with a limit | Parallel.ForEachAsync or SemaphoreSlim |
| CPU-heavy work over a collection | Parallel.ForEach, PLINQ |
| Increment or swap a single value | Interlocked |
| Protect a synchronous block | lock |
| Protect a block that awaits | SemaphoreSlim |
| Shared dictionary or queue | ConcurrentDictionary, ConcurrentQueue |
| Background work queue | Channel<T> |
Common mistakes
- Calling
.Resultor.Wait()on tasks (“sync over async”). - Using
async voidoutside event handlers. - Passing an
asynclambda toParallel.ForEachorList.ForEach. - Sharing one
DbContextacross concurrent tasks. - Using
lockaround code that awaits (it does not compile) or replacing it withMonitortricks instead ofSemaphoreSlim. - Firing off
Task.Runwithout awaiting or observing it, so exceptions are lost. - Starting unbounded numbers of concurrent requests against an external API.



