.NET Development

Thread pool starvation in ASP.NET Core 10: caused, measured and fixed

Team Nippysoft
• • 14 min read
Thread pool starvation in ASP.NET Core 10: caused, measured and fixed

"Measure first. Identify the bottleneck. Optimize the right layer. Benchmark again." That's how Raheemulla Shariff sums up his .NET performance interview cheatsheet on LinkedIn, and thread pool starvation sits among his mid-level topics. This article runs that whole loop on that one problem: I trigger it with .Result under load, measure it with dotnet-counters, fix it with await and measure again.

Along the way, three things showed up that I didn't expect. The dotnet-counters CSV misleads you about the thread count unless you know how to read it. The help .NET 6 added for .Result switches off when the thread pool sees system memory as high. And Thread.Sleep performs far better than .Result, even though both block. Everything was measured on one machine: .NET 10.0.14 (SDK 10.0.403), Windows 11, 12 logical processors and system memory at 82%. The numbers belong to this machine and serve as an example; the pattern is what repeats.

What starvation is and why .Result causes it

Microsoft's official tutorial defines it: "ThreadPool starvation occurs when the pool has no available threads to process new work items and it often causes applications to respond slowly." It also names the usual suspect, calling .Result on an asynchronous task: "This is the sync-over-async code pattern, which is known to block threads and is the most common cause of ThreadPool starvation." The ASP.NET Core best practices turn it into a rule: "Do not block asynchronous execution by calling Task.Wait or Task<TResult>.Result."

The thread that calls .Result sits blocked waiting for the query. When the query finishes, its continuation needs another free pool thread to run, and that thread is busy with another request that also blocked on its own .Result. Every blocked thread waits for a continuation that needs another thread, and every thread is blocked the same way. The pool adds threads slowly, and each new thread may pick another request from the queue that blocks as well.

With .Result, the continuation waits for a thread that never comes With .Result, the continuation waits for a thread that never comes .Result thread blocked on .Result the query finishes continuation is queued no free thread await thread returns to the pool the query finishes continuation is queued any thread runs it

The experiment

The API fakes the same 200 ms database query written three ways: with await, with .Result, and with Thread.Sleep standing in for a synchronous driver. There's also a /health endpoint that never blocks, to see whether starvation slows down the innocent too:

// A small API with the same 200 ms "database call" written three ways.
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); // no logging providers, as in the measured runs

var app = builder.Build();

// Fixed: the thread goes back to the pool while the query runs.
app.MapGet("/orders/async", async () =>
{
    var order = await FakeDatabase.GetOrderAsync(42);
    return Results.Ok(order);
});

// Sync-over-async: the thread waits blocked on .Result.
app.MapGet("/orders/sync-over-async", () =>
{
    var order = FakeDatabase.GetOrderAsync(42).Result;
    return Results.Ok(order);
});

// Plain blocking call: Thread.Sleep stands in for a synchronous driver or file API.
app.MapGet("/orders/blocking", () =>
{
    var order = FakeDatabase.GetOrderBlocking(42);
    return Results.Ok(order);
});

// Trivial endpoint that never blocks: shows that starvation slows down everything.
app.MapGet("/health", () => Results.Ok("ok"));

app.Run();

public sealed record Order(int Id, decimal Total);

public static class FakeDatabase
{
    public static readonly TimeSpan Latency = TimeSpan.FromMilliseconds(200);

    public static async Task<Order> GetOrderAsync(int id)
    {
        await Task.Delay(Latency);
        return new Order(id, 99.90m);
    }

    public static Order GetOrderBlocking(int id)
    {
        Thread.Sleep(Latency);
        return new Order(id, 99.90m);
    }
}

A custom program generates the load: 100 clients in a closed loop for 20 seconds, each one sending a request, waiting for the answer and sending the next, with a 30 s timeout. Another task calls /health every 250 ms. With no blocking, the theoretical ceiling is 100 clients over 0.2 s, about 500 requests per second.

There are five scenarios: the three endpoints plus two .Result variants I explain below, one with SetMinThreads(250) and one with a runtime switch that changes how the pool reacts to memory.

The results

ScenarioRequests in 20 sErrorsPer secondp50p99/health maxThreads (median under load)
.Result100100330009 ms30010 ms30019 ms24.5
Thread.Sleep1994097646 ms7119 ms1430 ms30
await (the fix)94000467214 ms357 ms170 ms15
.Result + SetMinThreads(250)94000464214 ms398 ms195 ms119
.Result + IgnoreMemoryUsage58000287214 ms7929 ms7931 ms103.5

"Per second" divides the requests by how long the whole test took, waiting for the timeouts included; that's why .Result shows 3.

In the run behind the tables, not a single .Result request completed in 20 seconds. The 100 you see are the timeouts at the end:

requests=100 errors=100 rps=3
latency ms: p50=30009 p95=30009 p99=30010 max=30010
/health ms: p50=30019 max=30019 samples=1
completed per second: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 100

That extreme doesn't always repeat. In seven more runs on the same machine, with the post's code and with the test code, .Result completed between 250 and 431 requests in 20 seconds, in waves, with a median latency of 5 to 6 s. The memory section explains what it depends on.

In that run, even /health, which blocks nothing, took 30 s to answer. With await, the same API served 467 requests per second, close to the 500 ceiling, with a 214 ms median latency and 13 to 15 threads most of the time.

Thread.Sleep also blocks the thread for 200 ms, yet it manages 97 per second. The difference is what each one waits for: Thread.Sleep wakes up on its own, without needing another pool thread, and frees its thread when it's done. .Result waits for a continuation that needs a free thread, and there isn't one.

If an endpoint that does nothing, like /health, gets slow under load, suspect the thread pool before the database.

Measuring with dotnet-counters, and the CSV trap

The official tool is dotnet-counters. monitor is enough to watch live; to keep the values and compare them later, use collect with the three thread pool metrics:

dotnet-counters monitor -n StarvationLab
dotnet-counters collect -p <pid> --refresh-interval 1 --format csv --counters "System.Runtime[dotnet.thread_pool.thread.count,dotnet.thread_pool.queue.length,dotnet.thread_pool.work_item.count]"
dotnet-counters collect -p <pid> --refresh-interval 1 --format csv --counters "EventCounters\System.Runtime[threadpool-thread-count,threadpool-queue-length]"

The three metrics come from the built-in .NET runtime metrics, available since .NET 9: the threads that exist (dotnet.thread_pool.thread.count), the queued work items (dotnet.thread_pool.queue.length) and the items completed since the process started (dotnet.thread_pool.work_item.count).

Here's the trap. In the CSV from dotnet-counters 10.0.750501, all three come out with type Rate and a name ending in / 1 sec. But the thread count and the queue length also come out as the difference from the previous second, not as a value. These are the raw lines for the first loaded second of .Result:

11/06/2026 07:52:03,System.Runtime,dotnet.thread_pool.thread.count ({thread} / 1 sec),Rate,10
11/06/2026 07:52:03,System.Runtime,dotnet.thread_pool.queue.length ({work_item} / 1 sec),Rate,98
11/06/2026 07:52:03,System.Runtime,dotnet.thread_pool.work_item.count ({work_item} / 1 sec),Rate,203

Read as is, it looks like there are 1 or 2 threads and a negative queue. The classic EventCounters from the same run, threadpool-thread-count and threadpool-queue-length, give the real value. The table joins both CSV files by second:

Timethread.count in the CSVThreads (EventCounters)queue.length in the CSVQueue (EventCounters)
07:52:0310139898
07:52:04215-296
07:52:05116-195
07:52:06117095
07:52:07118-194
07:52:08119-193
07:52:09221-192
07:52:1012223115

My rule: in CSV, add up the differences or also collect the EventCounters, which report the value. You can't mix both in one list; dotnet-counters rejects it with Error parsing --counters argument: Using the same provider name with and without the EventCounters\ prefix in the counter list is not supported. So you need two collect sessions.

What to look for, according to the tutorial: "The key signals that ThreadPool starvation is currently a performance bottleneck are the slow and steady increase of ThreadPool threads and CPU Usage much less than 100%." Often, though not always, there's also a long queue with few completed items. With .Result, the thread growth and the long queue both show up: threads grow by one per second, the queue goes past 100 and completed items stay at zero.

In the dotnet-counters CSV, thread.count and queue.length are per-second differences. A 1 in the thread column means "one more thread than before", not "one thread".

Why the .NET 6 help never arrived: memory

Since .NET 6, the pool reacts faster to this pattern. The tutorial says so: "Starting in .NET 6, ThreadPool heuristics were modified to scale up the number of ThreadPool threads much faster in response to certain blocking Task APIs." The runtime source shows how: when a pool thread blocks on one of those waits, the pool creates up to one extra thread per processor without delay (12 here) and then keeps adding them with a delay that starts at 25 ms and never goes past 250 ms.

So why did it grow by one thread per second in the run behind the tables, the slow pace the tutorial describes as "further threads are added 1-2 per second"? Because that help comes with a condition. The same code compares memory usage, plus an estimated stack per thread, with 80% of the GC's high memory load threshold (memoryLimitBytes * 8 / 10) and, above it, adds no threads for blocking.

Both values come from GCMemoryInfo (HighMemoryLoadThresholdBytes and MemoryLoadBytes) in PortableThreadPool.cs, and the pool doesn't read them all the time. It takes them when its gate thread starts ("Initialize memory usage and limits, and register to update them on gen 2 GCs"), reads them again on two or three of the first garbage collections, whatever their generation, and after that only on generation 2 collections. The registration of that callback sums it up: "Schedule 'callback' to be called in the next GC. If the callback returns true it is rescheduled for the next Gen 2 GC". In two runs of an unpublished copy of the API, whose sampler also reads what the pool stores through reflection, the value goes from 0, because before any collection GCMemoryInfo reports a load of 0, to 38.6 GB with the first generation 0 collection, and no generation 2 one at all:

sample t=2s threads=3 pending=0 completed/s=0 gen2GCs=0 memoryLoadGB=0.0 highLoadThresholdGB=38.6 gen0GCs=0 poolSeesUsageGB=0.0 poolLimitGB=38.6
sample t=3s threads=12 pending=0 completed/s=202 gen2GCs=0 memoryLoadGB=39.0 highLoadThresholdGB=38.6 gen0GCs=1 poolSeesUsageGB=38.6 poolLimitGB=38.6

Until the pool sees memory as high, the help works. And under load, the first collection arrives within seconds.

On this machine, under load, the threshold was 38.6 GB and usage was 35.2 GB, above the 30.9 GB that 80% stands for; since the threshold is 90% of the 42.9 GB available, here the cutoff kicks in at 72% memory use. To check that the cutoff was the cause, I repeated the scenario changing only the switch the code reads, System.Threading.ThreadPool.Blocking.IgnoreMemoryUsage=true in runtimeconfig.json. Threads went from 12 to 45 in one second and to 102 in eight, and from there the API served about 500 requests per second:

completed per second: 0 0 0 0 0 0 0 100 400 500 500 400 500 500 400 500 500 500 400 500 100

That fits the other runs. In all seven repetitions the help kicked in during the first second (from 3-6 to 24-31 threads), but after that threads grew by only one or two per second, the same pace as when the pool sees memory as high, and .Result completed only a few hundred requests. In a test copy that forces a collection at startup, so the pool sees memory from the start, there was no jump: from 4 to 12 threads and then one per second.

I'm not recommending the switch. The runtime configuration describes it this way: "By default, the rate of thread injection in response to blocking is limited by heuristics that determine whether there is sufficient physical memory available". The source explains the 80% margin: after the cutoff, the pool "may have to continue creating threads slowly to prevent a deadlock". Enabling the switch on a server with little memory removes that protection. Don't count on the .NET 6 help: a server with its memory taken goes back to the old behavior as soon as the pool notices.

SetMinThreads hides the symptom

The other well-known escape is raising the thread minimum. With ThreadPool.SetMinThreads(250, ...) and the same .Result, the API served 464 requests per second, nearly the same as await. But with 119 threads instead of 13 to 15, and each one adds its estimated stack to the usage the pool compares with the memory cutoff.

The SetMinThreads documentation presents it as a stopgap: "You can use SetMinThreads to increase the minimum number of threads, such as to temporarily work around issues where some queued work items or tasks block thread pool threads." And the tutorial reminds you that "Each thread also consumes memory".

If you see a server settled at many more threads than cores with CPU far from 100%, look for a .Result, a .Wait() or a GetAwaiter().GetResult() before touching the thread minimum.

The fix: await all the way, and measure again

The change is one line, plus async on the lambda:

// before
var order = FakeDatabase.GetOrderAsync(42).Result;
// after
var order = await FakeDatabase.GetOrderAsync(42);

The best practices ask for it across the whole chain: "The entire call stack is asynchronous in order to benefit from async/await patterns." And they warn against the shortcut of wrapping sync code: "Do not use Task.Run to make a synchronous API asynchronous."

Measuring again with the same command: 467 requests per second, 0 errors, a 357 ms p99, an empty queue and 13 to 15 threads while the load lasts.

If you fan out work with Task.WhenAll or Parallel.ForEachAsync, as in the .NET 10 concurrency post, the same applies: a single .Result inside that work blocks one pool thread per task.

Finding the .Result in a real app

In the experiment I know where the .Result is. In a real app it tends to sit where an await doesn't fit: constructors, synchronous dependency injection factories or the body of a lock, where the language doesn't allow it. To find it, the tutorial suggests two tools I didn't try here. dotnet-stack report -n <process> dumps the stacks of every thread; in its example, the blocked threads show Task.SpinThenBlockingWait and GetResultCore above the guilty method. And dotnet-trace, since .NET 9, has the WaitHandleWait event for these blocks.

What isn't tested

  • Only Windows 11 with 12 logical processors. I didn't test Linux, containers or container memory limits.
  • I didn't measure CPU. The "CPU much less than 100%" signal comes from the tutorial, not from these runs.
  • I didn't measure when the pool reads memory in the seven earlier runs. The IgnoreMemoryUsage variant, which changes only that switch, shows that the cutoff is the cause.
  • I didn't try dotnet-counters monitor live, dotnet-stack or dotnet-trace. I don't know whether the CSV differences are intended, or whether monitor shows the same; I only measured that the CSV comes out that way.

Frequently asked questions

Is GetAwaiter().GetResult() better than .Result?

Not for starvation. Both block the thread until the task finishes, and the tutorial lists them together, with Task.Wait, as sync-over-async calls.

Should I raise SetMinThreads while I fix the code?

As a temporary stopgap it can help, and that's how the documentation presents it. But in these runs it cost 119 threads against 15, and it hides the problem you need to remove.

Why does an endpoint that never blocks get slow too?

Because it shares the thread pool. In the run behind the tables, with .Result, /health took 30 s: its request waited for a free thread like all the others.

Conclusion

"Measure first" works when you know what to look at. With .Result under load, the API completed zero requests in 20 seconds in the run behind the tables and a few hundred in others; with await, 467 per second on 15 threads. Along the way you need to know that the dotnet-counters CSV gives differences instead of values, that the .NET 6 help switches off when the pool sees memory as high, and that SetMinThreads hides the problem at the cost of a hundred extra threads.

Search your code today for .Result, .Wait() and GetAwaiter().GetResult() on a request path, and for synchronous I/O too: a synchronous database driver, File.ReadAllText or HttpClient.Send. The Thread.Sleep row shows it costs as well: 97 per second against 467. Replace them with await and the driver's async version, and repeat the measurement with the same command.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code