ASP.NET Core applications are designed to handle many concurrent requests using a relatively small number of threads. The .NET Thread Pool manages these threads and provides them to application code whenever work needs to be executed.
However, when application code blocks too many Thread Pool threads, new requests and background operations may have to wait for an available thread. This condition is known as Thread Pool starvation.
Thread Pool starvation can make an application appear slow even when the server has sufficient CPU and memory resources. API requests may take several seconds to complete, background jobs may execute late, and response times may become unpredictable under load.
The problem is particularly difficult to identify because the application may work perfectly during development and fail only when multiple requests execute concurrently.
This article explains how Thread Pool starvation occurs in ASP.NET Core, how to recognize its symptoms, and how to investigate it using dotnet-counters, dotnet-stack, and dotnet-trace.
Understanding the .NET Thread Pool
The .NET Thread Pool is a collection of worker threads managed by the runtime. Instead of creating a new operating system thread for every operation, .NET reuses existing threads to execute work items.
ASP.NET Core uses the Thread Pool to execute many application operations, including:
- Processing incoming HTTP requests.
- Executing application callbacks.
- Running scheduled and background operations.
- Continuing asynchronous operations after awaited work completes.
- Executing tasks submitted through Task.Run.
Consider an API endpoint that retrieves customer information from a database.
app.MapGet("/customers/{id}", async (
int id,
AppDbContext dbContext) =>
{
var customer = await dbContext.Customers
.FindAsync(id);
return customer is null
? Results.NotFound()
: Results.Ok(customer);
});
When the application reaches FindAsync, the database operation can continue asynchronously without requiring the current Thread Pool thread to remain blocked while waiting for the database response.
The thread becomes available to execute other work. When the database operation completes, the application continuation is scheduled to resume.
This is one of the main advantages of asynchronous programming in ASP.NET Core.
However, if application code blocks threads while waiting for asynchronous operations, the Thread Pool can run out of immediately available workers.
What Is Thread Pool Starvation?
Thread Pool starvation happens when the runtime does not have enough available Thread Pool threads to execute queued work promptly.
For example, imagine an API receiving hundreds of concurrent requests. Each request calls an asynchronous database method but waits for its result using .Result instead of await.
Every blocked request occupies a Thread Pool thread.
As more requests arrive, the number of available threads decreases. New work items remain in the Thread Pool queue until additional threads become available.
The runtime can create more threads to compensate, but thread creation takes time and additional threads consume memory and scheduling resources.
The result is increased request latency and reduced application throughput.
A simplified representation looks like this:
Incoming HTTP Requests
|
v
ASP.NET Core
|
v
.NET Thread Pool
|
+--------------------+
| |
v v
Available Threads Blocked Threads
| |
v v
Process Requests Waiting on .Result
|
v
Thread Pool Queue
|
v
Increased Latency
Thread Pool starvation is different from high CPU usage. An application can experience starvation while CPU usage remains relatively low because many threads are waiting rather than performing useful work.
Common Causes of Thread Pool Starvation
Before using diagnostic tools, understand the coding patterns that commonly cause this problem.
Blocking Asynchronous Operations With .Result
One of the most common causes is calling .Result on a Task.
Consider this endpoint:
app.MapGet("/customer", () =>
{
var customer = GetCustomerAsync().Result;
return Results.Ok(customer);
});
The GetCustomerAsync method performs asynchronous work, but .Result blocks the current thread until the operation completes.
When many requests execute this endpoint simultaneously, many Thread Pool threads can become blocked.
The correct implementation uses await:
app.MapGet("/customer", async () =>
{
var customer = await GetCustomerAsync();
return Results.Ok(customer);
});
With await, the current thread can return to the Thread Pool while the asynchronous operation is waiting.
Using Task.Wait()
Task.Wait() has a similar problem.
public void ProcessOrder()
{
ProcessOrderAsync().Wait();
}
This blocks the calling thread until the asynchronous operation finishes.
Use an asynchronous method throughout the call chain:
public async Task ProcessOrderAsync()
{
await ProcessOrderAsyncInternal();
}
The method name in this simplified example is illustrative; in an actual implementation, use distinct names for the public operation and its internal processing method.
Using GetAwaiter().GetResult()
Some developers use GetAwaiter().GetResult() instead of .Result because it generally avoids the AggregateException wrapping behavior associated with Task.Result.
However, it still blocks the calling thread.
var result = GetDataAsync()
.GetAwaiter()
.GetResult();
It should not be treated as a performance-friendly alternative to await.
Using Thread.Sleep()
Thread.Sleep blocks the current thread for the specified duration.
For example:
app.MapGet("/report", () =>
{
Thread.Sleep(5000);
return Results.Ok("Report completed");
});
Every request occupies a Thread Pool thread for five seconds.
If the application receives many concurrent requests, the blocked threads can cause starvation.
When an asynchronous delay is appropriate, use Task.Delay:
app.MapGet("/report", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5));
return Results.Ok("Report completed");
});
This avoids blocking a Thread Pool thread during the delay.
Task.Delay is not a replacement for actual report processing. The example simply demonstrates the difference between a blocking wait and an asynchronous wait.
Holding Locks During Long Operations
Locks can also contribute to thread starvation when threads wait for a shared resource.
Consider:
private readonly object _lock = new();
public void UpdateData()
{
lock (_lock)
{
Thread.Sleep(3000);
// Update shared data.
}
}
Only one thread can enter the protected section at a time. Other requests may block while waiting for the same lock.
Avoid holding locks during database calls, HTTP requests, or other long-running operations.
For asynchronous coordination, use an appropriate asynchronous synchronization mechanism, such as SemaphoreSlim with WaitAsync, and keep the protected operation as short as possible.
Recognizing Thread Pool Starvation Symptoms
Thread Pool starvation usually appears as a combination of performance problems rather than one isolated metric.
Common symptoms include:
- API response times increase under concurrent load.
- Request throughput decreases even though CPU usage is relatively low.
- Thread Pool thread count increases continuously.
- Work items remain queued for longer periods.
- Background services execute jobs later than expected.
- Database and HTTP operations appear slower because request processing is delayed.
- Application performance improves after a restart but gradually degrades under load.
A high Thread Pool thread count alone does not prove starvation. The runtime may legitimately use more threads for a particular workload.
Look for a combination of increasing thread count, queued work, blocked thread stacks, and degraded request performance.
Monitor Thread Pool Metrics With dotnet-counters
The first diagnostic step is to monitor runtime counters while the application is experiencing slow responses.
Install dotnet-counters:
dotnet tool install --global dotnet-counters
List running .NET processes:
dotnet-counters ps
Monitor the target application:
dotnet-counters monitor --process-id 12345
Replace 12345 with the actual process ID.
For .NET 9 and later, the runtime exposes metrics such as:
| Metric | What it tells you |
|---|
| dotnet.thread_pool.thread.count | Current number of Thread Pool threads |
| dotnet.thread_pool.queue.length | Number of work items waiting in the Thread Pool |
| dotnet.thread_pool.work_item.count | Number of work items processed |
| dotnet.process.cpu.time | CPU time consumed by the process |
| dotnet.monitor.lock_contentions | Monitor lock contention activity |
For older .NET versions, dotnet-counters may display the corresponding System.Runtime EventCounters using different names.
How to Interpret the Metrics
Suppose an ASP.NET Core application shows the following pattern during load testing:
| Measurement | Normal operation | During suspected starvation |
|---|
| Thread Pool thread count | 20 | 140 |
| Queue length | 0 | 180 |
| CPU usage | 35% | 40% |
| Average API latency | 150 ms | 4 seconds |
These values are illustrative, not universal diagnostic thresholds.
The combination of a growing thread count, queued work, and increased latency suggests that the application may be blocking Thread Pool threads.
The relatively low CPU usage is another useful clue. The application is not necessarily spending its time performing CPU-intensive calculations. It may be waiting for blocked threads to become available.
Compare the metrics over time rather than relying on a single snapshot.
Use dotnet-stack to Find Blocked Threads
Once the counters indicate possible starvation, inspect the Thread Pool thread stacks.
Install the diagnostic tool:
dotnet tool install --global dotnet-stack
Capture thread stack information:
dotnet-stack report --process-id 12345
Review the output for repeated blocking patterns.
For example, you may find stacks containing methods such as:
System.Threading.ManualResetEventSlim.Wait
System.Threading.Tasks.Task.SpinThenBlockingWait
System.Threading.Tasks.Task.InternalWaitCore
System.Threading.Tasks.Task`1.GetResultCore
These methods can indicate that threads are synchronously waiting for asynchronous work to complete.
You may also find stacks involving:
System.Threading.Monitor.Enter
System.Threading.Monitor.Wait
System.Threading.SemaphoreSlim.Wait
These can indicate lock contention or other synchronization-related blocking.
The important step is to trace the stack back to application code. A runtime method appearing in a stack does not automatically mean that the runtime is responsible for the problem.
If many Thread Pool threads show similar blocked stacks, investigate the common application operation causing them to wait.
Use dotnet-trace for Intermittent Problems
Sometimes starvation happens only during specific workloads. A stack report captures the current state of the application, so it may miss an intermittent blocking operation.
In this situation, dotnet-trace can collect runtime events over a period of time.
Install the tool:
dotnet tool install --global dotnet-trace
Collect a trace:
dotnet-trace collect \
--process-id 12345 \
--duration 00:00:30
The generated trace can be opened in supported performance analysis tools.
For .NET 9 and later, the WaitHandleWait runtime event is particularly useful when investigating blocking operations. It can help identify waits caused by sync-over-async patterns and synchronization mechanisms.
For example, a trace may reveal that a frequently executed API method calls Task.Wait or waits on a monitor lock.
This provides more useful information than simply knowing that the Thread Pool has many threads.
Use dotnet-stack for obvious, continuously occurring blocking behavior. Use dotnet-trace when you need to capture behavior over time.
Fix Thread Pool Starvation by Removing Blocking Calls
The most effective solution is usually to remove unnecessary synchronous blocking from frequently executed application paths.
Consider this service:
public class CustomerService
{
private readonly AppDbContext _dbContext;
public CustomerService(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public Customer? GetCustomer(int id)
{
return _dbContext.Customers
.FirstOrDefaultAsync(x => x.Id == id)
.Result;
}
}
The service uses an asynchronous Entity Framework Core operation but blocks the calling thread to retrieve the result.
Change the method to return a Task:
public class CustomerService
{
private readonly AppDbContext _dbContext;
public CustomerService(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Customer?> GetCustomerAsync(
int id,
CancellationToken cancellationToken)
{
return await _dbContext.Customers
.FirstOrDefaultAsync(
x => x.Id == id,
cancellationToken);
}
}
Then update the API endpoint:
app.MapGet("/customers/{id:int}", async (
int id,
CustomerService customerService,
CancellationToken cancellationToken) =>
{
var customer = await customerService.GetCustomerAsync(
id,
cancellationToken);
return customer is null
? Results.NotFound()
: Results.Ok(customer);
});
Now the asynchronous pattern continues from the HTTP endpoint through the service and into the database operation.
Avoid fixing the problem by simply wrapping synchronous work in Task.Run and immediately awaiting it:
await Task.Run(() => SomeBlockingOperation());
This still consumes a Thread Pool thread while the synchronous operation is running. It adds scheduling overhead without making the underlying operation asynchronous.
If a legacy synchronous API must be used, consider moving that work to a dedicated worker or process when appropriate, rather than allowing it to block request-processing threads under heavy load.
Use Asynchronous APIs Throughout the Request Pipeline
Fixing one .Result call is not always enough. Thread Pool starvation can originate from any frequently executed part of the request pipeline.
Review the complete execution path:
- Controller and minimal API endpoints.
- Application services.
- Database repositories.
- HTTP client calls.
- File operations.
- Cache access.
- Logging providers.
- Third-party SDK integrations.
Prefer asynchronous APIs for I/O operations whenever available.
For example, use:
await File.ReadAllTextAsync(
filePath,
cancellationToken);
Instead of:
var content = File.ReadAllText(filePath);
Use:
await httpClient.GetAsync(
requestUri,
cancellationToken);
Instead of blocking on an HTTP request.
Also avoid synchronous stream operations in ASP.NET Core request handling when asynchronous alternatives are available.
The goal is to keep Thread Pool threads available for other work while the application waits for external resources.
Avoid Increasing the Thread Pool Minimum as the First Fix
.NET provides APIs for configuring Thread Pool minimum and maximum thread counts.
For example:
ThreadPool.SetMinThreads(100, 100);
Increasing the minimum may reduce the time required for the runtime to create additional threads in some workloads. However, it does not remove the blocking code responsible for starvation.
Too many threads can increase memory usage and scheduling overhead. A larger thread pool can also hide the problem temporarily while leaving the application inefficient.
Use ThreadPool.SetMinThreads only after measuring the workload and understanding why the default behavior is insufficient.
Fixing synchronous blocking, lock contention, and unnecessary long-running work should come first.
Common Mistakes During Thread Pool Troubleshooting
Avoid these approaches when investigating performance problems:
- Assuming high CPU usage is required for Thread Pool starvation.
- Treating a high thread count as proof of starvation.
- Replacing every synchronous method with Task.Run.
- Increasing minimum Thread Pool threads without investigating blocking calls.
- Using .Result or Wait because the code works during development.
- Holding locks while waiting for database or network operations.
- Ignoring third-party libraries that perform synchronous I/O.
- Looking only at average request latency instead of queue length and thread behavior.
- Collecting a memory dump or trace without reproducing the relevant workload.
- Fixing one endpoint without reviewing the complete request pipeline.
A reliable diagnosis should connect the performance symptoms to actual blocked thread stacks and application code.
Best Practices for Preventing Thread Pool Starvation
- Use async and await consistently for I/O-bound operations.
- Avoid Task.Result, Task.Wait, and GetAwaiter().GetResult() in request-processing paths.
- Use asynchronous database and HTTP client APIs.
- Avoid Thread.Sleep in request handlers and recurring background operations.
- Keep locks short and avoid holding them during external calls.
- Use message brokers to move long-running work out of HTTP requests.
- Limit CPU-intensive and blocking workloads appropriately.
- Monitor Thread Pool queue length and thread count.
- Use dotnet-stack for continuous blocking issues and dotnet-trace for intermittent problems.
- Include realistic concurrent load tests in performance testing.
Advantages and Disadvantages of Asynchronous Processing
| Advantages | Disadvantages |
|---|
| Releases threads while waiting for I/O | Requires consistent async design across the call chain |
| Supports higher request concurrency | Async code can be harder to debug initially |
| Reduces unnecessary thread blocking | Does not make CPU-intensive work execute faster |
| Improves scalability under I/O workloads | Legacy synchronous libraries may limit the benefits |
| Helps reduce Thread Pool pressure | Requires careful cancellation and exception handling |
Asynchronous programming is particularly beneficial for I/O-bound workloads. CPU-intensive operations still consume processing resources and may require separate scheduling or background processing strategies.
Summary
Thread Pool starvation is a common performance problem in ASP.NET Core applications that block too many worker threads. It can cause slow API responses, growing request queues, delayed background operations, and unpredictable application performance.
Start by monitoring Thread Pool metrics using dotnet-counters. Look for increasing thread counts, queued work items, and degraded response times. Use dotnet-stack to inspect continuously blocked threads and dotnet-trace to investigate intermittent blocking behavior.
The most common solution is to remove sync-over-async code and use asynchronous database, HTTP, and file operations throughout the request pipeline. Also review locks, third-party libraries, and long-running operations that may occupy Thread Pool threads unnecessarily.
The objective is not to create more threads. It is to keep existing Thread Pool threads available to perform useful work, allowing ASP.NET Core to handle concurrent requests efficiently.
ASP.NET Core.NET Thread Poolthread pool starvationasynchronous programmingdotnet-countersdotnet-traceperformance diagnostics
Join the conversation! Your thoughts help the community grow.