Skip to content

.NET 11 thread pool: workers spin full budget after spurious wake-ups, +40-85 % CPU per request vs .NET 10 for request/response socket workloads #137494

Open

Description

@romanett

Description

After moving an OPC UA server and client (https://github.com/OPCFoundation/UA-.NETStandard) from .NET 10 to .NET 11, CPU time per request rose substantially, with identical allocations and an identical number of thread-pool work items per request. The extra time is entirely user-mode spinning in the thread pool's LowLevelLifoSemaphore.

Comparing System.Private.CoreLib 10.0.15 with 11.0.0:

  • UnfairSemaphoreSpinLimit changed from 70 spin iterations to 1024 units of Backoff.Exponential.
  • A worker that was woken but found no work (spurious dispatch) skips the spin only when more than SpuriousDispatchNoSpinThreshold = ProcessorCount * 2 / 3 workers are processing. In our workload, fewer workers than that are busy, so every spurious wake-up costs a full spin.
  • Spurious wake-ups are frequent in request/response code. A common source is ThreadPool.UnsafeQueueUserWorkItem(..., preferLocal: true), or a ManualResetValueTaskSourceCore with RunContinuationsAsynchronously, issued by a thread that runs the item itself as soon as it returns to the pool. The enqueue still signals a worker, which then finds nothing.

Configuration

  • .NET 11.0.0 vs .NET 10.0.15, Windows 11 x64.
  • 24 logical processors (AMD hybrid: 8 + 16).
  • Two processes on loopback TCP: a server, and a load client with 20 connections, each with one request in flight (closed loop).
  • Workstation concurrent GC on both sides; otherwise default settings.

Data

Medians of 4 rotated rounds per configuration, discarding runs with other load on the machine. CPU is per request, measured in each process (Process.TotalProcessorTime / completed requests).

Workload Metric .NET 10 .NET 11 .NET 11 + DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0
Read 1 value req/s 214k 184k (−14 %) 222k (vs .NET 11: +9 %)
server µs/req 45.1 52.2 44.7
client µs/req 36.3 42.6 33.0
Write 100 values server µs/req 253 386 (+52 %) 210
client µs/req 112 181 (+61 %) 84
Browse client µs/req 84 120 (+43 %) 66

Other observations:

  • DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=46 (hex, = 70) brings CPU back to the .NET 10 level as well, but without the throughput gain.
  • DOTNET_ThreadPool_UnfairSemaphoreWakeCooldown=0 has no measurable effect.
  • Thread-pool work items per request (ThreadPool.CompletedWorkItemCount) are the same on both runtimes (client 3.0, server 2.1–4.0). Kernel CPU per request is unchanged; the whole increase is user mode.
  • Thread-time samples (EventPipe) on the .NET 11 client show LowLevelLifoSemaphore.MaybeWakeWaiterSlow at 22 % of on-CPU samples (server 6 %). That is the CAS loop with exponential backoff on the signalling side, which runs inline on the thread that queues work. On .NET 10 the comparable ReleaseCore was about 10 %.

Regression?

Yes, compared with .NET 10.0.15 (CPU efficiency). Throughput at this load level ranges from −14 % (small requests) to +5–10 % (larger ones).

Analysis / suggestion

The ⅔-of-processors threshold seems too high for moderately loaded request/response servers: most wake-ups there are spurious, and each one spins the full 1024-unit budget. Setting the threshold to 0 both removes the extra CPU and improves throughput. Options:

  • a lower default threshold;
  • a spin budget that shrinks with the recent rate of spurious dispatches;
  • not signalling a worker for a preferLocal item when the queuing thread is about to return to the dispatch loop.

The MaybeWakeWaiterSlow backoff on the signalling path is also worth a look, since it adds latency to the thread that produces the work.

Reproduction

  1. Build the load harness for both runtimes, as described in https://github.com/OPCFoundation/UA-.NETStandard/blob/master/perf/README.md:
    • CustomTestTarget=net10.0 dotnet build perf/ServerLoadHarness -c Release
    • CustomTestTarget=net11.0 dotnet build perf/ServerLoadHarness -c Release
  2. Run the same command with each build, alternating between the two:
    • ServerLoadHarness run --sessions 20 --duration 12 --warmup 6 --scenario write --nodes 100
  3. Compare the per-op: cpuUs (server) and client-per-op: cpuUs lines.
  4. To check the setting, set DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 for the client and SERVER_DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 for the server child.

Workaround applied on our side: OPCFoundation/UA-.NETStandard#5078. It removes one preferLocal enqueue per client request, which recovers about a quarter to a third of the client regression.

Activity

  1. added
    untriaged
    on Nov 13, 2026
  2. dotnet-policy-service commented on Nov 13, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @VSadov
    See info in area-owners.md if you want to be subscribed.

  3. lahma commented on Nov 18, 2026

    @lahma

    Another workload with the same cause, in a single process with no sockets: Quartz.NET's job scheduler firing no-op jobs from its in-memory store. On .NET 11 it loses throughput as well as CPU. SpuriousDispatchNoSpinThreshold=0 removes the loss and leaves .NET 11 faster than .NET 10.

    Shape. One async loop takes a permit from a SemaphoreSlim(10), then does about a microsecond of work under a System.Threading.Lock. It then calls Task.Factory.StartNew(..., TaskScheduler.Default). The work item takes the same lock briefly and releases the permit. Ten workers at most are processing, below the default threshold of ProcessorCount * 2 / 3 = 21 on this machine. So every spurious wake-up spins the full budget.

    Machine. AMD Ryzen 9 5950X (16 cores, 32 logical), Windows 11 x64, workstation concurrent GC. The same net10.0 app runs on 10.0.15, and on 11.0.0 through DOTNET_ROLL_FORWARD=LatestMajor. Each run is 25 s, with two rounds in rotated order, on an otherwise idle machine:

    Run ns per firing Process CPU per firing Pool threads
    .NET 10 1,686 / 1,705 13.3 / 13.4 µs 23-24
    .NET 11 2,205 / 2,152 (+29 %) 23.3 / 20.6 µs (+64 %) 13-14
    .NET 11, DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 1,497 / 1,503 (-11 % vs .NET 10) 8.0 / 7.9 µs 12
    .NET 11, DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=0 1,703 / 1,587 7.7 / 7.2 µs 12
    .NET 10, DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=0 1,686 / 2,415 6.3 / 9.1 µs 21 / 37

    EventPipe sampled thread time (Microsoft-DotNETCore-SampleProfiler, 1 ms), two captures per runtime. These are thread-ns per firing summed over all threads; [cpu] means the sample was in managed code, [native] that it was outside it.

    Frame .NET 10 .NET 11
    LowLevelLifoSemaphore.Wait [cpu] 2,013 12,182
    LowLevelLifoSemaphore.WaitForSignal [native] (parked) 23,177 0
    LowLevelLifoSemaphore.Block [cpu + native] 0 3,976
    WaitHandle.WaitForMultipleObjectsIgnoringSyncContext 0 2,588
    Lock.TryEnterSlow [cpu] 720 2,878
    QueryPerformanceCounter + Environment.TickCount64 [cpu] 0 1,234
    LowLevelLifoSemaphore.MaybeWakeWaiterSlow [cpu] 0 448

    On .NET 10, idle workers park. On .NET 11 they spin, and the spinners also contend for the application's Lock. That lock is on the scheduler loop's critical path, so throughput drops too, not only CPU.

    A standalone repro (no Quartz) is the shape above in about 60 lines. Its loop and work items share a lock with about 1 µs of work in it. Over 3 s runs it gives 1,382-1,392 ns and 8.9-9.0 µs CPU per dispatch on .NET 10, and 1,532-1,551 ns and 16.0-16.2 µs on .NET 11. Without the shared lock, .NET 11 costs more CPU per dispatch but no throughput. With SpuriousDispatchNoSpinThreshold=0, the CPU per dispatch falls to 4.9-5.6 µs.

    Program.cs

    Run as TpRepro 3 800 (3 s, 800 iterations of locked work), on .NET 10 and then with DOTNET_ROLL_FORWARD=LatestMajor for the same net10.0 build on .NET 11.

    // Minimal shape of Quartz.NET's fire path dispatch, with no Quartz in it (#4214): one async loop that takes a
    // permit from a SemaphoreSlim of ten, hands a no-op work item to TaskScheduler.Default with Task.Factory.StartNew,
    // and goes round again; the work item gives the permit back. When all ten are out, WaitAsync completes
    // asynchronously and the loop resumes on a pool thread once a work item releases.
    //
    // Usage: TpRepro [seconds]   prints dispatches per second, ns per dispatch and process CPU per dispatch.
    using System.Diagnostics;
    
    int seconds = args.Length > 0 ? int.Parse(args[0]) : 10;
    // Second argument: iterations of work done under one shared Lock, by the loop before each dispatch and by
    // each work item before it releases, as RAMJobStore's lock is taken by the scheduler loop and by the
    // completing worker. 0 leaves the lock out.
    lockedWork = args.Length > 1 ? int.Parse(args[1]) : 0;
    const int MaxConcurrency = 10;
    
    SemaphoreSlim gate = new(MaxConcurrency);
    Action<object?> work = static state =>
    {
        if (lockedWork > 0)
        {
            lock (shared)
            {
                sink += Spin(lockedWork / 2);
            }
        }
    
        ((SemaphoreSlim) state!).Release();
    };
    
    // Warm-up, so the JIT, tiering and the pool's thread count have settled before anything is measured.
    await Run(gate, work, TimeSpan.FromSeconds(2));
    
    Process self = Process.GetCurrentProcess();
    TimeSpan cpuBefore = self.TotalProcessorTime;
    long started = Stopwatch.GetTimestamp();
    long dispatched = await Run(gate, work, TimeSpan.FromSeconds(seconds));
    TimeSpan elapsed = Stopwatch.GetElapsedTime(started);
    self.Refresh();
    TimeSpan cpu = self.TotalProcessorTime - cpuBefore;
    
    Console.WriteLine(
        $"{Environment.Version}: {dispatched:N0} dispatches in {elapsed.TotalSeconds:F1} s - {dispatched / elapsed.TotalSeconds:N0}/s, "
        + $"{elapsed.TotalNanoseconds / dispatched:N0} ns each, {cpu.TotalNanoseconds / dispatched:N0} ns CPU each, "
        + $"{ThreadPool.ThreadCount} pool threads");
    
    static async Task<long> Run(SemaphoreSlim gate, Action<object?> work, TimeSpan duration)
    {
        long until = Stopwatch.GetTimestamp() + (long) (duration.TotalSeconds * Stopwatch.Frequency);
        long count = 0;
        while (Stopwatch.GetTimestamp() < until)
        {
            await gate.WaitAsync().ConfigureAwait(false);
            if (lockedWork > 0)
            {
                lock (shared)
                {
                    sink += Spin(lockedWork);
                }
            }
    
            _ = Task.Factory.StartNew(work, gate, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            count++;
        }
    
        // Let the work items still out finish before the next phase.
        for (int i = 0; i < MaxConcurrency; i++)
        {
            await gate.WaitAsync().ConfigureAwait(false);
        }
    
        gate.Release(MaxConcurrency);
        return count;
    }
    
    // Work the JIT cannot remove: a short dependent chain whose result is kept.
    static long Spin(int iterations)
    {
        long x = iterations;
        for (int i = 0; i < iterations; i++)
        {
            x = (x * 6364136223846793005L) + 1442695040888963407L;
        }
    
        return x;
    }
    
    partial class Program
    {
        private static readonly Lock shared = new();
        private static int lockedWork;
        private static long sink;
    }
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <Optimize>true</Optimize>
      </PropertyGroup>
    
    </Project>

    Since the threshold scales with ProcessorCount, a workload with a fixed degree of concurrency is the worst case on a large machine, which is common for schedulers and bounded worker pools.

    The full Quartz.NET measurement, with the four-leg tables and the profile breakdown, is in quartznet/quartznet#4214 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Threadinguntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions