ASP.NET Core applications depend heavily on asynchronous execution to handle multiple requests efficiently. A single application instance can process many incoming requests because the framework does not need to dedicate one operating system thread to every request while it waits for an external operation to complete.
However, this efficiency depends on using the available threads correctly.
When application code blocks Thread Pool threads for long periods, the application may become slower even when CPU usage is relatively low. New requests may take longer to start, background tasks may become delayed, and operations that normally complete quickly may begin timing out.
This condition is known as Thread Pool starvation.
Thread Pool starvation is particularly difficult to troubleshoot because it does not always produce an obvious exception. The application may remain running, database connections may still be available, and CPU usage may appear normal. Yet response times continue increasing.
In this article, we will explore how Thread Pool starvation occurs in ASP.NET Core, how to identify its symptoms, how to investigate it using .NET diagnostics, and how to fix common causes in production applications.
Understanding the .NET Thread Pool
The .NET Thread Pool is a collection of reusable worker threads managed by the runtime.
Instead of creating a new operating system thread for every operation, .NET reuses existing threads to execute application work.
ASP.NET Core uses the Thread Pool for several activities, including:
- Processing application request work.
- Executing scheduled callbacks.
- Running continuations of asynchronous operations.
- Executing Task-based operations.
- Handling background work that uses Thread Pool scheduling.
For example, consider an API endpoint that retrieves customer information from a database.
[HttpGet("{id}")]
public async Task<IActionResult> GetCustomer(
int id,
CancellationToken cancellationToken)
{
var customer = await _customerService.GetByIdAsync(
id,
cancellationToken);
if (customer is null)
{
return NotFound();
}
return Ok(customer);
}
The database operation is asynchronous. While the application waits for the database response, the request does not need to keep a Thread Pool thread occupied simply to wait.
When the operation completes, its continuation can execute on an available Thread Pool thread.
This allows the application to use its worker threads more efficiently.
The problem starts when application code blocks these threads unnecessarily.
What Is Thread Pool Starvation?
Thread Pool starvation occurs when available Thread Pool threads are insufficient to execute the work waiting in the Thread Pool.
It commonly happens when existing worker threads spend too much time blocked instead of completing their assigned operations.
Imagine an ASP.NET Core application receiving 500 requests at the same time. Each request needs to call an external service.
If the application uses synchronous blocking calls, many Thread Pool threads may become occupied while waiting for those external operations.
New requests and continuations then have to wait for available threads.
The runtime can inject additional Thread Pool threads when necessary, but adding threads takes time and cannot always keep up with sudden increases in blocked work.
As a result, the application may experience:
- Increasing HTTP response times.
- Delayed request execution.
- Background workers processing tasks more slowly.
- More queued Thread Pool work.
- Timeouts in unrelated application operations.
- Low or moderate CPU usage despite poor application responsiveness.
Thread Pool starvation is not the same as high CPU usage.
High CPU usage usually means threads are busy executing calculations. Starvation often means threads are unavailable because they are blocked or otherwise occupied.
Common Causes of Thread Pool Starvation
Understanding the causes is the first step toward finding the problem.
Using Task.Result and Task.Wait
One of the most common causes is synchronously waiting for an asynchronous operation.
Consider this example:
public Customer GetCustomer(int id)
{
return _customerService
.GetByIdAsync(id)
.Result;
}
The Result property blocks the current thread until the asynchronous operation completes.
In an ASP.NET Core application, this can unnecessarily occupy a Thread Pool thread.
If many requests execute this code simultaneously, a large number of worker threads may become blocked.
The same problem can occur with Task.Wait.
public IActionResult GetCustomer(int id)
{
var task = _customerService.GetByIdAsync(id);
task.Wait();
return Ok(task.Result);
}
The better approach is to make the calling method asynchronous.
public async Task<IActionResult> GetCustomer(int id)
{
var customer = await _customerService.GetByIdAsync(id);
return Ok(customer);
}
Using await allows the method to suspend while the operation is incomplete instead of blocking the current thread.
Using Thread.Sleep Inside Request Processing
Thread.Sleep blocks the current thread for the specified duration.
For example:
public IActionResult GetStatus()
{
Thread.Sleep(3000);
return Ok("Completed");
}
Every request executing this method occupies a Thread Pool thread for three seconds.
If the application receives many concurrent requests, blocked threads can accumulate quickly.
When a delay is necessary inside asynchronous application code, use Task.Delay.
public async Task<IActionResult> GetStatus(
CancellationToken cancellationToken)
{
await Task.Delay(
TimeSpan.FromSeconds(3),
cancellationToken);
return Ok("Completed");
}
Task.Delay does not require a Thread Pool thread to remain blocked for the entire waiting period.
However, replacing Thread.Sleep with Task.Delay is not a solution for unnecessary delays. If the application does not need to wait, remove the delay entirely.
Calling Synchronous APIs From Asynchronous Code
Sometimes an application uses an asynchronous controller but calls synchronous methods inside its service layer.
For example:
public async Task<Customer> GetCustomerAsync(int id)
{
var customer = _repository.GetCustomer(id);
return customer;
}
The method is marked async, but the database operation is still synchronous.
Adding async to a method declaration does not automatically make its operations asynchronous.
Use asynchronous database APIs where supported.
public async Task<Customer?> GetCustomerAsync(
int id,
CancellationToken cancellationToken)
{
return await _dbContext.Customers
.FirstOrDefaultAsync(
customer => customer.Id == id,
cancellationToken);
}
The same principle applies to HTTP calls, file operations, and other I/O-bound work.
Blocking Background Workers
Thread Pool starvation can also originate from background services.
Consider a worker that repeatedly performs blocking operations.
protected override Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
ProcessNextItem();
Thread.Sleep(1000);
}
return Task.CompletedTask;
}
This implementation occupies a Thread Pool thread for the lifetime of the worker.
For a long-running background service, use asynchronous execution.
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessNextItemAsync(stoppingToken);
await Task.Delay(
TimeSpan.FromSeconds(1),
stoppingToken);
}
}
The asynchronous version allows the worker to wait without continuously blocking a Thread Pool thread.
Recognizing Thread Pool Starvation in Production
Thread Pool starvation can be difficult to identify from application logs alone.
A request timeout does not necessarily mean that the database or external API is slow. The request may simply be waiting for an available Thread Pool thread before its code can continue.
Look for a combination of symptoms rather than relying on one metric.
| Symptom | What it may indicate |
|---|
| High HTTP response times | Requests are waiting for execution or downstream operations |
| Low CPU usage with poor responsiveness | Worker threads may be blocked |
| Increasing Thread Pool thread count | Runtime may be adding threads to handle blocked work |
| Increasing work item queue length | Work is waiting for available Thread Pool threads |
| Delayed background tasks | Shared Thread Pool resources may be under pressure |
| Intermittent request timeouts | Execution delays may be affecting request completion |
These symptoms are indicators, not proof. A slow database, network problems, connection pool exhaustion, or other resource constraints can produce similar behavior.
The investigation should combine runtime metrics with traces, logs, and thread stack information.
Monitoring Thread Pool Metrics
.NET exposes runtime metrics that help developers investigate Thread Pool behavior.
Important metrics include:
- Thread Pool thread count.
- Thread Pool queue length.
- Completed work item count.
- Thread Pool worker thread availability.
These metrics can be collected through .NET runtime diagnostics and monitoring systems that support the runtime's metrics infrastructure.
A particularly useful metric is the Thread Pool queue length. It indicates how many work items are waiting for execution.
If the queue length continues increasing while requests become slower, the application may not have enough available workers to process incoming work.
Thread count should also be examined over time. A rapidly increasing thread count can indicate that the runtime is responding to blocked workers.
However, a high thread count alone does not prove starvation. It must be evaluated alongside queue length, request latency, and thread activity.
Investigating Thread Pool Starvation With dotnet-counters
The dotnet-counters tool provides a convenient way to monitor runtime metrics without changing application code.
First, identify the running ASP.NET Core process.
dotnet-counters ps
The command displays available .NET processes.
Next, monitor the runtime counters for the application.
dotnet-counters monitor --process-id 12345 --counters System.Runtime
Replace 12345 with the actual process ID.
The output includes runtime information such as Thread Pool thread count, queue length, CPU usage, and garbage collection metrics.
While monitoring, reproduce the workload that causes the slowdown or observe the application during a naturally occurring traffic spike.
Look for these patterns:
- Thread Pool queue length increases and remains elevated.
- Thread Pool thread count grows while requests become slower.
- Completed work does not increase at the same rate as incoming work.
- CPU usage remains relatively low compared with the level of application slowdown.
This combination can provide strong evidence of Thread Pool starvation.
The exact counter names and available measurements can vary with the runtime version and diagnostic tooling. Always inspect the counters available in the environment being monitored.
Investigating Blocked Threads With dotnet-dump
Runtime counters help identify suspicious behavior, but they do not always show which methods are blocking threads.
For deeper investigation, collect a process dump and inspect the managed thread stacks.
The dotnet-dump tool can collect a dump from a running .NET process.
dotnet-dump collect --process-id 12345
After collecting the dump, analyze it.
dotnet-dump analyze <dump-file>
Inside the analysis environment, useful commands include:
threads
clrstack
The threads command lists managed threads, while clrstack displays managed call stacks.
Look for repeated stacks containing methods such as:
- Task.Wait
- Task`1.get_Result
- Thread.Sleep
- Monitor.Enter
- ManualResetEventSlim.Wait
These methods are not automatically evidence of a bug. Some synchronization and waiting operations are legitimate.
The important question is whether a large number of Thread Pool workers are blocked while the application has significant work waiting to execute.
For example, if many threads show the same synchronous HTTP or database waiting pattern, inspect the application code responsible for those calls.
Understanding the Difference Between Blocking and CPU-Bound Work
Not every Thread Pool performance problem is caused by synchronous blocking.
CPU-bound operations can also consume Thread Pool resources.
Consider an API that performs a large amount of image processing directly during request execution.
public IActionResult ProcessImage(byte[] image)
{
var result = PerformExpensiveCalculation(image);
return Ok(result);
}
The method may use substantial CPU time.
In this situation, adding more Thread Pool threads does not necessarily improve performance because the actual limitation may be CPU capacity.
The troubleshooting approach should be different.
| Area | Blocking workload | CPU-bound workload |
|---|
| Main problem | Threads spend time waiting | Threads spend time calculating |
| CPU usage | May remain low | Often high |
| Common examples | Task.Wait, Thread.Sleep, synchronous I/O | Image processing, compression, complex calculations |
| Main improvement | Use asynchronous APIs and remove unnecessary blocking | Optimize algorithms and control concurrency |
| Additional option | Separate long-running work | Move suitable work to a dedicated processing system |
Identifying the actual bottleneck prevents developers from applying the wrong optimization.
Using Task.Run Carefully in ASP.NET Core
A common attempt to fix blocking code is to wrap it in Task.Run.
For example:
public Task<Customer> GetCustomerAsync(int id)
{
return Task.Run(() =>
_repository.GetCustomer(id));
}
This does not make the synchronous database operation non-blocking.
The operation still occupies a Thread Pool thread while it runs. Task.Run simply schedules the blocking work onto another Thread Pool thread.
In ASP.NET Core, this can add scheduling overhead without solving the underlying problem.
For I/O-bound work, prefer genuinely asynchronous APIs.
Task.Run can be appropriate for certain CPU-bound operations when there is a clear reason to move the calculation away from the current execution path. However, it should not be used as a general replacement for asynchronous I/O.
For large or expensive CPU workloads, a controlled background processing system may be a better design.
Preventing Thread Pool Starvation in ASP.NET Core
Preventing starvation requires consistent application design rather than increasing the number of available threads.
The following practices are particularly important.
Use Asynchronous APIs Throughout the Call Chain
If a controller calls an asynchronous service, the repository and downstream operations should also use asynchronous APIs where available.
Avoid converting asynchronous operations back into synchronous execution with Result or Wait.
Avoid Blocking Calls in Request Processing
Remove unnecessary Thread.Sleep, synchronous I/O, and long-running blocking operations from request handlers.
If a request needs to initiate lengthy work, consider submitting it to a background processing system and returning an appropriate response.
Control Concurrency for CPU-Heavy Work
Running too many CPU-intensive operations concurrently can reduce application responsiveness.
Use explicit concurrency limits for expensive workloads.
Avoid Uncontrolled Background Task Creation
Repeatedly creating fire-and-forget tasks can increase pressure on the Thread Pool and make failures difficult to track.
Use a managed background worker, bounded queue, or durable job system when work needs controlled execution.
Monitor Runtime Metrics Continuously
Collect Thread Pool metrics alongside HTTP request duration, database performance, and application errors.
Monitoring over time makes it easier to distinguish a temporary traffic spike from a recurring resource problem.
Do Not Increase Thread Pool Minimums as the First Fix
The runtime provides APIs for configuring Thread Pool minimum and maximum thread counts.
For example:
ThreadPool.SetMinThreads(
workerThreads: 100,
completionPortThreads: 100);
Increasing the minimum number of worker threads may help in specific situations, but it does not remove the underlying blocking behavior.
Too many threads can increase memory usage and scheduling overhead.
Before changing Thread Pool settings, identify the blocking code and understand why existing workers are unavailable.
Testing for Thread Pool Starvation
Performance tests should include scenarios that expose blocking behavior.
A useful test plan includes:
- Send a large number of concurrent requests to the affected endpoint.
- Compare response times with the endpoint using asynchronous and synchronous operations.
- Monitor Thread Pool thread count and queue length during the test.
- Introduce realistic delays in downstream dependencies.
- Observe whether background processing becomes delayed when HTTP traffic increases.
- Capture a dump when the application becomes unresponsive and inspect blocked thread stacks.
Use a realistic workload. A test that sends only a few requests may never expose starvation because the Thread Pool has enough available workers to handle them.
Also avoid relying on one performance-test result. Repeat tests under different concurrency levels and compare runtime metrics.
Summary
Thread Pool starvation occurs when .NET worker threads become unavailable to execute incoming work, often because application code blocks them for extended periods.
In ASP.NET Core, common causes include Task.Result, Task.Wait, Thread.Sleep, synchronous database operations, and blocking background workers. These patterns can cause request delays and timeouts even when CPU usage appears relatively low.
The first step in troubleshooting is to examine runtime metrics such as Thread Pool thread count and queue length. Tools such as dotnet-counters help identify suspicious behavior, while dotnet-dump can provide deeper information about blocked thread stacks.
The most effective solution is usually to remove unnecessary blocking, use asynchronous APIs throughout the call chain, and control expensive background workloads. Increasing Thread Pool minimums should be considered only after understanding the actual bottleneck.
By monitoring runtime behavior and designing application code around asynchronous execution, developers can reduce Thread Pool starvation and build ASP.NET Core applications that remain responsive under concurrent workloads.
Join the conversation! Your thoughts help the community grow.