skip to content

Why does the .NET thread pool add threads so slowly when a nightly image job's 64 work items each block on a synchronous upload, and what changes that?

level: seniorimportance: must knowfreq 58%

answer

  1. on demand only up to a minimum
  2. hill climbing measures throughput
  3. a check every 500 ms
  4. Task.Wait counts as cooperative blocking
  5. ThreadCount and PendingWorkItemCount

basics

~20 s

The pool creates threads on demand only up to its minimum, Environment.ProcessorCount; above it, a starvation check adds about one thread per half second for stuck work. Task.Wait-style blocking gets faster compensation. The fix is to stop blocking pool threads.

solid answer

~50 s

The pool creates worker threads without delay only up to its minimum, `Environment.ProcessorCount` by default. Above that, two mechanisms add threads: **hill climbing**, which moves the thread count according to the measured completion rate, and the **gate thread**, which wakes every 500 ms and, if queued work has gone undequeued for long enough, raises the target by one thread. A thread stuck in `Thread.Sleep` or a synchronous upload looks like slow work, so on a 16-core machine 64 blocking items climb by about one thread per half second, slower when CPU is busy, while the queue waits. Since .NET 6, blocking in `Task.Wait` or `.Result` notifies the pool, which then adds up to another processor-count of threads at once and more after growing delays. `ThreadPool.ThreadCount` and `ThreadPool.PendingWorkItemCount` show it; the cure is to stop blocking pool threads, and `ThreadPool.SetMinThreads` is a measured stopgap.

code

csharp · 19 lines
csharp
// Each work item blocks its pool thread for 3 seconds, the way a synchronous resize-and-upload call would.
bool cooperative = args.Length > 0 && args[0] == "wait";
int items = Environment.ProcessorCount * 4;

for (int i = 0; i < items; i++)
{
    ThreadPool.QueueUserWorkItem(_ =>
    {
        if (cooperative) Task.Delay(3000).Wait();   // Task.Wait tells the pool this thread is blocked
        else Thread.Sleep(3000);                    // the pool cannot tell this from slow work
    });
}

Console.WriteLine($"{(cooperative ? "Task.Wait" : "Thread.Sleep")}: {items} items, {Environment.ProcessorCount} cores");
for (int t = 0; t <= 2000; t += 500)
{
    Console.WriteLine($"t={t,4} ms  ThreadCount={ThreadPool.ThreadCount,3}  PendingWorkItemCount={ThreadPool.PendingWorkItemCount,3}");
    Thread.Sleep(500);
}

go deeper

for a junior

Know that blocking a thread pool thread keeps it from running other work, and that the pool does not add a new thread instantly for each waiting item.

for a middle

Explain the minimum worker count, hill climbing and the gate thread's starvation check, and why sleeping or synchronous I/O starves the pool.

for a senior

Diagnose starvation from ThreadCount, PendingWorkItemCount and low CPU, explain the Task.Wait compensation added in .NET 6, and order the fixes: remove blocking, bound it, move it off the pool, then tune minimums.

for a principal

Set the rule that pool threads never block on I/O in shared processes, because one component's blocking delays timers and continuations for every other component.

## The minimum, and what happens above it The managed thread pool keeps a **minimum worker count**, `Environment.ProcessorCount` by default (`ThreadPool.GetMinThreads`). Up to that number it creates a thread as soon as work is waiting. Above it, the pool deliberately grows slowly, because extra threads on a CPU-bound workload only add context switches. The runtime source has two mechanisms that raise the count past the minimum, and a third, newer one for a specific kind of blocking. Picture the nightly image job on a 16-core machine: 64 work items each resize an image and then upload it with a synchronous call that takes seconds. Sixteen items start at once; the other 48 sit in the queue while sixteen threads sleep in the network stack with the CPU nearly idle. ## Hill climbing: tuning for throughput **Hill climbing** samples the pool's completion rate at short, slightly randomised intervals (10 to 200 ms in the source), tries small changes to the thread count and moves toward the count that gives higher throughput. It is built for CPU-bound work and moves gradually. It cannot tell a thread blocked on a socket from a thread doing work, so a pool full of blocked threads gives it little signal to act on. ## Starvation detection: the gate thread A background **gate thread** wakes every 500 ms (`GateActivitiesPeriodMs`). If work items are waiting and nothing has been dequeued for long enough, it raises the thread target by **one** and starts a thread. "Long enough" is 500 ms while CPU utilisation is under 80 %, and the current thread goal multiplied by 1,000 ms when it is higher. In practice a starving pool with idle CPUs gains roughly one thread every half second, and a busy machine gains them far more slowly. The first run of the snippet below, 56 sleeping items on a 14-core machine, shows exactly that: - `ThreadCount` rose by one thread per 500 ms sample: 14, 15, 16, 17, 18. - `PendingWorkItemCount` fell by one per step, from 42 to 38. - The queue drains mostly because the original 14 threads finish their sleeps, not because the pool helped: injection added four threads in two seconds. ## Cooperative blocking: `Task.Wait` and `.Result` since .NET 6 When a pool thread blocks in `Task.Wait`, `.Result` or `GetAwaiter().GetResult()` on an unfinished task, the task's wait path tells the pool before it blocks. The pool then compensates much faster. The defaults in the runtime source: | Setting (`runtimeconfig.json`) | Default | Effect | |---|---|---| | `System.Threading.ThreadPool.Blocking.ThreadsToAddWithoutDelay_ProcCountFactor` | 1 | up to 1 × processor count extra threads with no delay | | `System.Threading.ThreadPool.Blocking.ThreadsPerDelayStep_ProcCountFactor` | 1 | after that, the delay grows every processor-count threads | | `System.Threading.ThreadPool.Blocking.DelayStepMs` | 25 | delay added per step | | `System.Threading.ThreadPool.Blocking.MaxDelayMs` | 250 | ceiling on the delay | The docs add that the rate also backs off when physical memory runs short (`...Blocking.IgnoreMemoryUsage`, .NET 7, switches that off) and that this compensation currently applies only to work items waiting on another task. In the second run, the same 56 items blocking in `Task.Wait` took the pool from 14 to 28 threads immediately and to 57 within 1.5 seconds. `Thread.Sleep`, synchronous file or socket I/O and lock waits get no such notification; they rely on the gate thread alone. Compensation is not a cure either: every blocked thread still holds its stack while it waits. ## Why the whole process suffers The pool is shared. While the job's items hog it, timer callbacks, continuations after `await` and any `Parallel` loop in the same process wait in the same queue. A job that blocks pool threads therefore looks like a slow job and a sluggish process at once. ## What to change 1. **Stop blocking.** Use the upload client's asynchronous API and await it, so the thread returns to the pool during the wait (the async lessons cover how). 2. **Bound the blocking work.** If a synchronous API is unavoidable, cap how many calls run at once, for example with `ParallelOptions.MaxDegreeOfParallelism`, instead of queuing all 64. 3. **Move permanent blocking off the pool.** A loop that blocks for the life of the process belongs on a dedicated thread, such as a `TaskCreationOptions.LongRunning` task. 4. **Raise the minimum as a stopgap.** `ThreadPool.SetMinThreads`, the `System.Threading.ThreadPool.MinThreads` setting or the `ThreadPoolMinThreads` project property lets the pool create threads up to the new minimum without the injection delay. The docs caution that an unnecessarily high minimum can make everything slow; it also hides the blocking rather than removing it. To confirm the diagnosis, sample `ThreadPool.ThreadCount`, `ThreadPool.PendingWorkItemCount` and `ThreadPool.CompletedWorkItemCount`: a count that climbs in half-second steps, a queue that stays long and low CPU together mean starvation. The same values appear as thread pool counters in the runtime's diagnostics tools, which the tracing material covers.

  • Why does ThreadPool.SetMinThreads(200, ...) make the slow ramp-up disappear, and what does it cost?
    Below the minimum the pool creates a thread as soon as work is waiting, so raising it to 200 removes the 500 ms injection delay for the first 200 threads. Each extra thread still reserves a stack and competes for the CPU when many wake together, the docs warn that a needlessly high minimum hurts performance, and the blocking that caused the problem is still there.
  • Why does the thread pool add threads faster when work items block in Task.Wait than in Thread.Sleep?
    Since .NET 6, a task wait notifies the pool that its thread is about to block, and the pool releases or creates replacement threads, the first processor-count of them without delay. `Thread.Sleep` and synchronous I/O send no such signal, so only the gate thread's starvation check, about one thread per half second, responds.
  • Which values show thread pool starvation from inside a .NET process?
    `ThreadPool.ThreadCount` climbing in small steps, `ThreadPool.PendingWorkItemCount` staying high, and `ThreadPool.CompletedWorkItemCount` growing slowly, all while CPU is low. Sampled every half second, that pattern separates starvation from CPU saturation, where the queue is long but every core is busy.

  • The thread pool creates a thread immediately for every queued work item
  • Hill climbing can tell a blocked thread from a busy one
  • Thread.Sleep in a work item gets the same fast compensation as Task.Wait
  • A very high SetMinThreads value is a free, permanent fix
  • Thread pool starvation always shows up as 100% CPU