Skip to content

Runtime async has major perf regression since .NET 11 RC2 #135738

Description

@hez2010

Description

I'm running the runtime async benchmarks, but it seems that since .NET 11 rc2, we are getting major performance regressions and it's even wrose in the latest release/11.0 GA branch.

Benchmark .NET 10 .NET 11 RC1 .NET 11 RC2 .NET 11 daily
Synchronous baseline 0.332 ns 0.332 ns 0.333 ns 0.332 ns
Async, no suspension 6.466 ns 0.395 ns 0.393 ns 0.399 ns
Completed Task await 4.006 ns 0.333 ns 0.330 ns 0.336 ns
Completed ValueTask await 0.754 ns 0.333 ns 0.336 ns 0.332 ns
Task.Yield suspension 302.58 ns 34.30 ns 184.69 ns 249.03 ns
ThreadPool continuation 373.83 ns 104.87 ns 266.91 ns 341.99 ns
TaskCompletionSource continuation 499.52 ns 115.66 ns 381.54 ns 530.47 ns
Async state-machine chain 712.21 ns 86.76 ns 281.17 ns 374.03 ns

Benchmark code: https://gist.github.com/hez2010/d1802e7c7ab10e21a92dcba2afe0a58d

Activity

  1. added
    tenet-performance
    on Oct 14, 2026
  2. added
    untriaged
    on Oct 14, 2026
  3. dotnet-policy-service commented on Oct 14, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-threading-tasks
    See info in area-owners.md if you want to be subscribed.

  4. hez2010 commented on Oct 14, 2026

    @hez2010
    ContributorAuthor

    Bisected to #132908 (and #132765).

    Setting DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 restore the perf for me. I guess the heuristics need further tuning.

    Without setting DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 we are spending a lot of time in System.Threading.LowLevelLifoSemaphore.WaitSlow.

    cc: @VSadov

  5. hez2010 commented on Oct 15, 2026

    @hez2010
    ContributorAuthor

    I experimented with it a bit and came up with a heuristic that dramatically improves performance on this benchmark, bringing it on par with RC1 without regressing the cases addressed by #132765:

    It uses where recent work came from to decide whether an idle worker should keep spinning.

    The old rule looked only at NumProcessingWork. A worker leaves that count before spinning, so one productive worker could coexist with several idle spinners while the pool still appeared lightly loaded (i.e. a low count can allow excessive spinning on empty dispatches).

    The new rule tracks the last work request from a thread without work-queue thread-local state, including I/O pollers. The timestamp is updated before request coalescing, so fresh external activity is always recorded. If no external activity has occurred in the last dispatch quantum, idle workers park sooner instead of competing with productive workers. Otherwise, the existing spinning policy is preserved.

    diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerThread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerThread.cs
    index 60153fe1ef6..961f09de1e2 100644
    --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerThread.cs
    +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerThread.cs
    @@ -44,9 +44,9 @@ private static short DetermineSpuriousDispatchNoSpinThreshold()
                     // At more than this working threads we start parking threads after a spurious dispatch.
                     short DefaultSpuriousDispatchNoSpinThreshold = (short)(Environment.ProcessorCount * 2 / 3);
    
    -                // When a worker is invited to dispatch work items but finds none, it may park without spinning first.
    -                // That is only preferable while more than this number of workers are still processing work and can take
    -                // the next request. Set to 0 to park without spinning when at least one other worker is still processing work.
    +                // After a recent external thread request, park an empty dispatch without spinning when more than
    +                // this number of workers are still processing work. Set to 0 to park when at least one other worker
    +                // is processing work. Without a recent external request, empty dispatches park at any worker count.
                     short threshold =
                         AppContextConfigHelper.GetInt16Config(
                             "System.Threading.ThreadPool.SpuriousDispatchNoSpinThreshold",
    @@ -187,10 +187,14 @@ private static bool WorkerDoWork(PortableThreadPool threadPoolInstance)
                         // See `TryIncrementProcessingWork` for details about Saturated state.
                     } while (!TryRemoveWorkingWorker(threadPoolInstance, out numProcessingWork));
    
    -                // Parking right away after a spurious dispatch is only worthwhile while other workers remain
    -                // processing work and can take the next request. When few workers are left, the next request is
    -                // likely to come to this thread, so it is cheaper to spin and stay available.
    -                return spurious && numProcessingWork > SpuriousDispatchNoSpinThreshold;
    +                // Spinners have already left NumProcessingWork, so a low processing count alone does not
    +                // imply that another poller is useful. Preserve polling capacity for recent external producers,
    +                // which can introduce another burst after the queues drain. For work produced entirely by
    +                // workers, park empty dispatches promptly instead of competing with the productive workers.
    +                return spurious &&
    +                    (numProcessingWork > SpuriousDispatchNoSpinThreshold ||
    +                     (uint)(Environment.TickCount -
    +                         Volatile.Read(ref threadPoolInstance._separated.lastExternalWorkItemTimeMs)) > ThreadPoolWorkQueue.DispatchQuantumMs);
                 }
    
                 // returns true if the worker is shutting down
    diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.cs
    index ec284dce761..8d1bf7e7874 100644
    --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.cs
    +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.cs
    @@ -122,6 +122,11 @@ private struct CacheLineSeparated
                 /// <safety>This int occupies its own offset in the explicit layout and overlaps no other field, so accessing it cannot forge a managed reference or read out of bounds.</safety>
                 [FieldOffset(Internal.PaddingHelpers.CACHE_LINE_SIZE * 4 + sizeof(int))]
                 public safe int gateThreadRunningState;
    +
    +            // Last worker request from outside the work-queue dispatcher, including coalesced requests.
    +            /// <safety>This int occupies its own cache-line offset and overlaps no other field, so accessing it cannot forge a managed reference or read out of bounds.</safety>
    +            [FieldOffset(Internal.PaddingHelpers.CACHE_LINE_SIZE * 5)]
    +            public safe int lastExternalWorkItemTimeMs;
             }
    
             private long _currentSampleStartTime;
    @@ -486,6 +491,17 @@ private bool ShouldAdjustMaxWorkersActive(int currentTimeMs)
    
             internal void EnsureWorkerRequested()
             {
    +            if (ThreadPoolWorkQueueThreadLocals.threadLocals == null)
    +            {
    +                // Record external producers even when another request is already outstanding.
    +                // Avoid publishing the same timestamp repeatedly within a clock tick.
    +                int currentTimeMs = Environment.TickCount;
    +                if (Volatile.Read(ref _separated.lastExternalWorkItemTimeMs) != currentTimeMs)
    +                {
    +                    Volatile.Write(ref _separated.lastExternalWorkItemTimeMs, currentTimeMs);
    +                }
    +            }
    +
                 // Only one worker is requested at a time to mitigate Thundering Herd problem.
                 if (_separated._hasOutstandingThreadRequest == 0 &&
                     Interlocked.Exchange(ref _separated._hasOutstandingThreadRequest, 1) == 0)

    I think this should be simple enough to be put in .NET 11.

    /cc: @VSadov

  6. hez2010 commented on Oct 15, 2026

    @hez2010
    ContributorAuthor

    Benchmark of the above patch against RC1 and RC2:

    Async benchmark:

    Benchmark .NET 11 RC1 .NET 11 RC2 Patched
    Task.Yield suspension, ns/op 35.73 172.76 37.39
    ThreadPool continuation, ns/op 84.19 245.32 87.89
    TaskCompletionSource continuation, ns/op 98.60 361.80 102.27
    Async state-machine chain, ns/op 77.56 251.05 76.57

    #135855 Multiplexed TCP: 64 callers, one connection, 5 µs work.

    Metric .NET 11 RC1 .NET 11 RC2 Patched
    Throughput, ops/s 742,598 799,014 806,936
    Client CPU, µs/op 8.627 9.594 8.971
    p99 latency, µs 192.0 204.8 192.0

    #132765 WebSocket workload: 100 connections, 1,000-byte echo, compression disabled.

    Metric .NET 11 RC1 .NET 11 RC2 Patched
    Throughput, requests/s 335,264 331,092 336,503
    Client + server CPU, µs/request 46.81 47.16 46.75
    p99 latency, µs 583.7 608.7 536.7

    Same #132765 WebSocket workload with four connections:

    Metric .NET 11 RC1 .NET 11 RC2 Patched
    Throughput, requests/s 115,050 112,737 114,360
    Client + server CPU, µs/request 57.45 106.55 108.69
    p99 latency, µs 64.5 70.8 62.8
  7. self-assigned this
    on Oct 23, 2026
  8. coderb commented on Nov 12, 2026

    @coderb

    The RC2 spin rule on an I/O-driven workload, and what a fix has to do

    The data below comes from #137300 (async SqlClient queries cost 50–110% more CPU per query on .NET 11). The workload is nothing like the microbenchmarks in this issue: every unit of work arrives as a socket completion. It shows the same cause, and it shows what a fix has to cover that a fix tuned to these microbenchmarks would not. Full tables and setup: #137300 (comment). Source references are to the v10.0.15 and v11.0.0 tags.

    What the data shows

    Closed loop of pooled-connection queries, SqlClient 7.1.1, identical SqlClient binary on both runtimes, 24 logical CPUs. Mean client CPU µs per query:

    Linux, 4 workers Linux, 16 workers Windows, 4 workers
    .NET 10.0.15 53.7 (65.6k q/s) 53.1 (128.5k q/s) 37.0
    .NET 11.0.0 80.8 (61.8k q/s) 58.6 (124.1k q/s) 77.8
    .NET 11, SpuriousDispatchNoSpinThreshold=0 31.8 (66.9k q/s) 28.7 (137.4k q/s) not run
    .NET 11, UnfairSemaphoreSpinLimit=0 21.4 (67.5k q/s) 24.6 (140.5k q/s) 27.7
    .NET 10, UnfairSemaphoreSpinLimit=0 28.0 (60.0k q/s) 33.6 (127.5k q/s) 18.2

    On Linux, the server runs on the client's machine, so spinning there also takes cores from the server. The CPU figures are the client's alone.

    1. The extra CPU is on the worker threads, in user mode. I measured per-thread CPU (/proc/self/task/*/stat, grouped by thread name) on Linux at 4 workers, in µs per query:

      • .NET TP Worker: 37.7 user / 13.7 kernel on .NET 10, against 70.7 user / 6.9 kernel on .NET 11.
      • .NET Sockets (the epoll thread): 0.8 / 0.9 against 1.0 / 1.3.

      Thread pool work items per query (5.0) and allocations per query are unchanged. More user time with less kernel time is what replacing yields with busy-spinning looks like. The workers also block more on .NET 11: 2.5–2.6 voluntary context switches per query, against 1.6–1.9 on .NET 10. So the extra spinning doesn't spare them the wait.

    2. On .NET 11 the spinning buys nothing in this loop, and on .NET 10 it bought something. The loop is closed, so a spin that picked up work sooner would show up as more queries/s. Turning spinning off raised .NET 11's throughput (61.8k to 67.5k q/s at 4 workers, 124.1k to 140.5k at 16) and lowered .NET 10's (65.6k to 60.0k at 4 workers).

    3. CPU tracks the semaphore spin limit. On .NET 11 (Linux, 4 workers) the total CPU per query at each UnfairSemaphoreSpinLimit was:

      Spin limit 0 100 296 598 1024 (default) 1298 4132
      CPU µs per query 22.5 31.8 45.8 60.8 ~80.8 90.5 116.1
      queries/s 65.1k 64.8k 62.9k 61.8k 61.8k 62.4k 68.6k

      The highest limit bought the most throughput of all the runs, at more than five times the CPU of no spinning at all. That trade is real: it just costs more here than it buys.

      A gotcha with that knob: the runtime parses DOTNET_ThreadPool_UnfairSemaphoreSpinLimit as hex (AppContextConfigHelper.cs line 255, NumberStyles.HexNumber), so =1024 means 4132 and =70 means 112. The limits above are the values the runtime actually used.

    The mechanism, from the source

    • The spin. .NET 11's LowLevelLifoSemaphore.WaitSlow spins up to DefaultSemaphoreSpinCountLimit = 1024 units (LowLevelLifoSemaphore.cs line 23). It's a pure Backoff.Exponential / Thread.SpinWait loop with no yield (line 116), "about 35 microseconds" by its own comment (line 22). It adds a 4 µs wake cooldown (line 26).
    • What it replaced. .NET 10 spun SemaphoreSpinCountDefault = 70 steps (PortableThreadPool.WorkerThread.cs line 18), doubled on Unix (LowLevelLifoSemaphore.cs line 99). After SpinSleep0Threshold = 10 steps (line 22) it alternated SpinWait with Sleep(0) (line 105, through LowLevelSpinWaiter). That is the kernel time .NET 10 shows and .NET 11 doesn't.
    • Who spins. A worker leaves the processing count (TryRemoveWorkingWorker, PortableThreadPool.WorkerThread.cs line 188) before it waits on the semaphore (line 127). So spinners are invisible to numProcessingWork, as noted above.
      • A worker that did some work and then found the queue empty always spins.
      • A worker woken to no work at all (a spurious dispatch) skips the spin only if numProcessingWork > SpuriousDispatchNoSpinThreshold (line 193). The threshold defaults to ProcessorCount * 2 / 3 (line 45): 16 on these machines, which 4 or 16 workers never exceed.
      • That is why SpuriousDispatchNoSpinThreshold=0 recovers most of the cost but not all of it: 31.8 against 21.4 µs per query with the semaphore spin off.
    • Where the work comes from. In I/O- and timer-driven programs, work is queued by threads outside the pool:
      • the Linux epoll thread (SocketAsyncEngine.Unix.cs line 308);
      • the Windows IOCP pollers (PortableThreadPool.IO.Windows.cs line 273);
      • the timer thread (TimerQueue.Portable.cs line 128, through EnqueueAtHighPriority, which calls EnsureWorkerRequested at ThreadPoolWorkQueue.cs line 688).

    What a fix has to do

    Each requirement comes with the evidence for it.

    1. Bound the CPU spent on spins that find no work, in I/O-driven workloads.
    2. Work whatever thread the work comes from. Socket completions and timer callbacks are queued from outside the pool (the code paths above).
      • A rule that keeps the RC2 policy whenever outside work arrived recently, like the patch above, never changes behavior for a socket-driven program or one with a timer firing within 30 ms (DispatchQuantumMs).
      • The patch's own WebSocket run with four connections shows it: 57.45 µs/request on RC1, 106.55 on RC2, 108.69 patched.
    3. Account for the workers already spinning. They aren't in numProcessingWork (lines 188 and 127), so any rule based on that count alone lets spinners pile up while the pool looks idle. At 4 workers, the spinning here comes to about 3 cores: 50 µs of CPU per query at 62k queries/s.
    4. Not grow with core count at fixed concurrency. With the threshold at ProcessorCount * 2 / 3, the same 4-worker program spins after every spurious dispatch on a 24-CPU machine, where it would not on a 4-CPU one.
    5. Cover more than spurious dispatches. A worker coming off real work always takes the full semaphore spin, and that remainder is visible in the data (31.8 against 21.4 µs per query at 4 workers, 28.7 against 24.6 at 16). The sweep (point 3) shows the spin length itself is a cost lever.
    6. Not be a single static threshold. In .NET 11 thread pool: multiplexed clients leave cores idle, 30–45% lower throughput than .NET 10 (RC1 and RC2) #135855's 64-caller, 5 µs-work cell, threshold 0 is the worst setting (625k ops/s against 668k default and 695k at 32767), and for StackExchange.Redis round trips it is the best (+5% against −14%). Here it cuts CPU per query by 60%. No single value serves all three.
    7. Keep what Increase spinning/polling aggressiveness in the thread pool in low-saturation scenarios #132765 restored. A warm worker for bursty, low-saturation latency: WebSocket echo went from 221k to 1,044k RPS with that PR, against 802k on .NET 10.
    8. Be judged on CPU per operation as well as throughput and latency. Here throughput moved by under 10% while CPU per query rose 50–110%. A benchmark reporting only RPS or ops/s, as most of those cited in these threads do, would not show this regression.

    Not explained by spinning

    On Windows, with UnfairSemaphoreSpinLimit=0, .NET 11 still costs more than .NET 10 (27.7 against 18.2 µs per query, in user time). On Linux it costs less (21.4 against 28.0). So there is a Windows-specific cost besides the spin. The runs were on a hybrid CPU without pinning, so that remainder isn't sized yet.

    Not tested

    • I have not built the patch above. Point 2 rests on the code paths cited and on the patch's own WebSocket row.
    • The 16-worker figures are one run each.
    • On Windows, SpuriousDispatchNoSpinThreshold=0, managed SNI, and P-core-pinned runs are still to do. I can run them, or a candidate fix built into CoreLib, if that would help.
  9. coderb commented on Nov 12, 2026

    @coderb

    @stephentoub could you please review this issue, it is a show stopper for us.

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

Metadata

Metadata

Assignees

Labels

area-System.Threading.Taskstenet-performanceuntriaged

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions