Skip to content

.NET 11 thread pool: multiplexed clients leave cores idle, 30–45% lower throughput than .NET 10 (RC1 and RC2) #135855

Open

Description

@mgravell

Description

A client where many callers share one socket and each does a few µs of its own CPU work per operation
loses 30–45% of its throughput on .NET 11 compared with .NET 10. The thread pool keeps far fewer
cores busy: on a 12-CPU cpuset, .NET 10 keeps about 11.5 busy, RC1 about 5.7 and RC2 about 7.8.
p99 latency is 4–8× worse.

This was found with StackExchange.Redis and reproduces without Redis:
https://github.com/seredis/dotnet11-threadpool-repro. That repo has a single-file Redis-free repro,
pinned SDK images, a grid runner, and raw results. Related: #135738 covers the same change
(#128606 → #132765/#132908) from the opposite direction.

Reproduction

git clone https://github.com/seredis/dotnet11-threadpool-repro && cd dotnet11-threadpool-repro
./run.py core          # Docker + Python only; or by hand, see the README

The repro is an echo server plus a client in which:

  • 64 callers share one TCP connection;
  • each caller writes a request and awaits a TaskCompletionSource created with
    RunContinuationsAsynchronously;
  • one read loop completes the callers in order;
  • each caller then spins for 5 µs.

The server and the client run on disjoint CPU sets.

Results

The table is the 64-caller, 5 µs-work cell. Each figure is the median of 3 interleaved runs of 10 s,
on a Ryzen 9 7900X with the client pinned to 12 CPUs.

ops/s vs .NET 10 cores busy p99 µs
.NET 10.0.12 1,029,128 11.56 86
11.0.0-rc.1.26425.128 573,273 −44.3% 5.69 688
11.0.0-rc.2.26504.105 667,782 −35.1% 7.76 360
RC2, SpuriousDispatchNoSpinThreshold=0 625,107 −39.3% 7.21 475
RC2, SpuriousDispatchNoSpinThreshold=32767 695,212 −32.4% 8.55 328

What else the runs show:

  • Runtime async is not involved. Compiling the app (and StackExchange.Redis) with
    runtime-async=on or off moves throughput by about 1%.
  • The knob doesn't recover it. No value of DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold
    gets close to .NET 10. The same holds when 78% of operations complete synchronously (a local
    cache hit), where the best value is still −30%, and with StackExchange.Redis v4's client-side
    cache, where the best is −22.5%.
  • Neither do min threads. SetMinThreads(32 or 128) makes RC2 about 8% slower. The pool already
    has 13–16 workers; they are parked while work is queued.
  • It depends on how many callers there are and how much they do. With 1 or 4 callers, RC2 is within
    5% of .NET 10. With 16 callers it is −16%, with 64 callers −36%, and with 256 callers −26%. At
    20 µs of work per operation the loss is −17% to −19%. With no work at all, .NET 11 matches
    .NET 10 throughput on far less CPU.
  • With 4 or 8 client CPUs, RC2 is worse than RC1: −29% and −32%, against RC1's −18% and −25%.
  • The threshold favours different workloads at each end. For StackExchange.Redis v4 with
    64 callers doing pure round trips, RC2's default is −14% vs .NET 10. Threshold 0 gives +5%.
    The same threshold 0 costs 7 points on the client-cache cell. This is the same pull Runtime async has major perf regression since .NET 11 RC2 #135738
    describes.

Analysis

RC2's #132765 recovers part of what #128606 cost in RC1. What remains doesn't respond to the
threshold at any value, so the parking decision that #132765 made tunable doesn't fully account for
it. #122726 (shorter LIFO semaphore spinning) and the rest of #128606 are the candidates I can see,
but I haven't bisected beyond RC1/RC2/the daily.

Possibly related: #93234

Configuration

  • .NET 10.0.12 vs 11.0.0-rc.1.26425.128 and 11.0.0-rc.2.26504.105, from the official SDK images
    pinned by digest. Each result records the exact runtime build.
  • Linux x64, kernel 7.1, Ryzen 9 7900X. The client is pinned to 12 CPUs.
  • Server GC.

Regression?

Yes, from .NET 10.

Activity

  1. added
    untriaged
    on Oct 15, 2026
  2. dotnet-policy-service commented on Oct 15, 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. added
    tenet-performance
    on Oct 15, 2026
  4. hez2010 commented on Oct 15, 2026

    @hez2010
    Contributor

    Actually, I'm not able to reproduce your results in my environment (i7-13700K):

    Client CPUs .NET 10 RC1 RC2 RC2 vs .NET 10
    12 735k ops/s 743k 799k +8.7%
    4 519k ops/s 516k 523k +0.7%

    Maybe it's somehow an AMD specific issue?

  5. kfrancis commented on Oct 15, 2026

    @kfrancis

    Data point from AMD, re the "AMD-specific?" question: Ryzen 9 9950X (Zen 5, 16C/32T), but under WSL2 (Windows 11 + Docker Desktop, kernel 6.18.33.2-microsoft-standard-WSL2), not bare metal. I don't reproduce the regression here, but I don't think this setup can show it. Details below.

    run.py core --server-cpus 0-7 --client-cpus 16-27 (client sees 12 CPUs = 6 SMT pairs; server on 4 other cores). Same pinned images, 3 × 10 s runs after a 3 s warmup, medians.

    64 callers, 5 µs work:

    row ops/s vs .NET 10 busy (of 12) p99 µs spread
    .NET 10 197,376 4.31 524 23.6%
    RC1 ra-off 203,082 +2.9% 3.14 475 6.6%
    RC2 ra-off 212,485 +7.7% 3.96 492 1.2%
    RC2, threshold 0 206,042 +4.4% 3.54 508 23.7%
    RC2, threshold 32767 200,945 +1.8% 3.87 524 35.4%

    Other cells, RC1 / RC2 vs .NET 10: 1 caller −23.2% / −12.5%; 64 callers no work +3.7% / −10.5%; 64 callers 20 µs work +1.5% / +5.8%; 78% local hits +2.4% / +1.8%.

    Caveat: .NET 10 only reaches ~197k ops/s with 4.3 of 12 cores busy (vs ~1.03M and 11.56 busy on the 7900X). So the client is never CPU-bound here; the bottleneck is likely WSL2 loopback/vCPU scheduling. The regression in the issue shows up as .NET 10 saturating cores and .NET 11 not, so this run can't really confirm or rule it out. Spreads are also high (up to ~60% in some cells). WSL2 vCPUs aren't pinned to physical cores, so --cpuset-cpus only pins inside the VM.

    The 1-caller cell does regress (RC1 −23%, RC2 −12.5%), in the same direction as the 7900X (−16.5% / −4.1%).

    I can rerun on bare-metal Linux on this box if that would help.

    Full summary.md

    core

    2026-10-15T11:28:27, AMD Ryzen 9 9950X 16-Core Processor, kernel 6.18.33.2-microsoft-standard-WSL2, server CPUs 0-7, client CPUs 16-27, 3 repeats of 10 s after 3 s warmup. Medians; the percentage is against the .NET 10 row (of the same library, for Redis) in the same cell. busy is CPU cores the client kept busy (process CPU time / wall time).

    1 caller

    row ops/s vs .NET 10 spread busy CPU us/op p50 us p99 us threads
    .NET 10 9,654 +0.0% 16.3% 1.61 166.41 90 180 4
    RC1 ra-off 7,410 -23.2% 6.0% 0.83 111.67 127 197 4
    RC1 ra-on 7,230 -25.1% 4.3% 0.83 114.68 131 205 4
    RC2 ra-off 8,451 -12.5% 14.1% 1.41 169.34 119 180 4
    RC2 ra-on 8,289 -14.1% 6.4% 1.40 168.30 119 180 4
    RC2 ra-off threshold=0 7,823 -19.0% 6.3% 1.04 133.80 123 197 4
    RC2 ra-off threshold=4 8,393 -13.1% 40.5% 1.41 168.55 119 180 5
    RC2 ra-off threshold=32767 8,358 -13.4% 14.8% 1.42 172.07 119 188 4

    64 callers

    row ops/s vs .NET 10 spread busy CPU us/op p50 us p99 us threads
    .NET 10 342,537 +0.0% 38.2% 2.60 7.59 172 377 14
    RC1 ra-off 355,164 +3.7% 21.3% 1.80 5.07 172 344 12
    RC1 ra-on 375,217 +9.5% 50.9% 1.85 4.93 164 328 12
    RC2 ra-off 306,441 -10.5% 51.6% 2.48 8.09 188 377 12
    RC2 ra-on 309,917 -9.5% 63.4% 2.54 8.20 180 393 14
    RC2 ra-off threshold=0 349,222 +2.0% 35.1% 1.96 5.63 164 360 12
    RC2 ra-off threshold=4 313,291 -8.5% 15.9% 2.46 7.86 180 360 13
    RC2 ra-off threshold=32767 313,883 -8.4% 9.6% 2.50 7.96 180 360 12

    64 callers, 5 us work

    row ops/s vs .NET 10 spread busy CPU us/op p50 us p99 us threads
    .NET 10 197,376 +0.0% 23.6% 4.31 22.03 311 524 14
    RC1 ra-off 203,082 +2.9% 6.6% 3.14 15.42 295 475 12
    RC1 ra-on 205,531 +4.1% 3.6% 3.19 15.50 295 459 12
    RC2 ra-off 212,485 +7.7% 1.2% 3.96 18.72 279 492 13
    RC2 ra-on 207,248 +5.0% 3.0% 3.98 19.10 295 508 12
    RC2 ra-off threshold=0 206,042 +4.4% 23.7% 3.54 17.22 295 508 12
    RC2 ra-off threshold=4 211,703 +7.3% 52.5% 3.80 17.93 279 492 13
    RC2 ra-off threshold=32767 200,945 +1.8% 35.4% 3.87 19.26 295 524 13

    64 callers, 20 us work

    row ops/s vs .NET 10 spread busy CPU us/op p50 us p99 us threads
    .NET 10 139,644 +0.0% 4.5% 5.87 42.16 426 1311 15
    RC1 ra-off 141,742 +1.5% 40.6% 5.05 35.62 442 590 13
    RC1 ra-on 129,689 -7.1% 51.5% 4.79 36.93 442 852 14
    RC2 ra-off 147,722 +5.8% 27.9% 5.78 39.36 410 918 14
    RC2 ra-on 135,892 -2.7% 61.3% 5.59 41.14 442 786 14
    RC2 ra-off threshold=0 141,706 +1.5% 19.0% 5.54 39.10 442 655 13
    RC2 ra-off threshold=4 149,046 +6.7% 12.8% 5.80 39.06 410 688 14
    RC2 ra-off threshold=32767 145,175 +4.0% 6.4% 5.78 39.87 410 819 15

    64 callers, 78% local hits, 1 us work

    row ops/s vs .NET 10 spread busy CPU us/op p50 us p99 us threads
    .NET 10 960,136 +0.0% 5.7% 4.26 4.43 0 410 13
    RC1 ra-off 983,297 +2.4% 9.7% 3.17 3.23 0 360 12
    RC1 ra-on 933,610 -2.8% 4.3% 3.18 3.41 0 393 11
    RC2 ra-off 977,623 +1.8% 6.7% 3.97 4.07 0 410 13
    RC2 ra-on 993,431 +3.5% 5.5% 4.00 4.03 0 393 12
    RC2 ra-off threshold=0 923,947 -3.8% 9.9% 3.51 3.80 0 442 12
    RC2 ra-off threshold=4 970,654 +1.1% 3.2% 3.81 3.92 0 410 12
    RC2 ra-off threshold=32767 993,712 +3.5% 5.0% 3.98 4.00 0 393 12

    What ran

    • .NET 10: 10.0.12-servicing.26422.108+95017c711e6afc1085133d440e42b4bd78155701 on Ubuntu 24.04.5 LTS; env {}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 0 runtime-async / 9 state-machine; System.Private.CoreLib 10 runtime-async / 0 state-machine
    • RC1 ra-off: 11.0.0-rc.1.26425.128+3551975be08744f0418857c5bed8ab1545c5dd47 on Ubuntu 26.04.1 LTS; env {}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC1 ra-on: 11.0.0-rc.1.26425.128+3551975be08744f0418857c5bed8ab1545c5dd47 on Ubuntu 26.04.1 LTS; env {}; Repro 5 runtime-async / 0 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC2 ra-off: 11.0.0-rc.2.26504.105+820230c386db5b0106c5430b3e5aee92a7826bf5 on Ubuntu 26.04.1 LTS; env {}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC2 ra-on: 11.0.0-rc.2.26504.105+820230c386db5b0106c5430b3e5aee92a7826bf5 on Ubuntu 26.04.1 LTS; env {}; Repro 5 runtime-async / 0 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC2 ra-off threshold=0: 11.0.0-rc.2.26504.105+820230c386db5b0106c5430b3e5aee92a7826bf5 on Ubuntu 26.04.1 LTS; env {'DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold': '0'}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC2 ra-off threshold=4: 11.0.0-rc.2.26504.105+820230c386db5b0106c5430b3e5aee92a7826bf5 on Ubuntu 26.04.1 LTS; env {'DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold': '4'}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine
    • RC2 ra-off threshold=32767: 11.0.0-rc.2.26504.105+820230c386db5b0106c5430b3e5aee92a7826bf5 on Ubuntu 26.04.1 LTS; env {'DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold': '32767'}; Repro 0 runtime-async / 5 state-machine; System.Net.Sockets 9 runtime-async / 0 state-machine; System.Private.CoreLib 101 runtime-async / 0 state-machine

    Processor count seen by the client: 12.

  6. hez2010 commented on Oct 15, 2026

    @hez2010
    Contributor

    @mgravell Since I cannot reproduce your result, maybe you can have a try on #135738 (comment) in your environment

  7. self-assigned this
    on Oct 20, 2026
  8. VSadov commented on Oct 23, 2026

    @VSadov
    Member

    I am able to repro a roughly 20% regression on the redis-free repro sample. (in WSL on an AMD VM).

  9. removed
    untriaged
    on Oct 26, 2026
  10. added this to the 12.0.0 milestone on Oct 26, 2026
  11. VSadov commented on Oct 28, 2026

    @VSadov
    Member

    @mgravell do the machines involved in this scenario have deep sleep enabled (aka powersave, C6 state, ...)

    Having deep sleep enabled/disabled may explain why not everyone can repro this.
    Deep sleep may affect how long it takes for a parked thread to wake and in a latency-sensitive scenario (i.e. client/server ping-pong like scenario) latency may gate the throughput.

    Deep sleep behavior may also vary with CPU. Another reason it may or may not reproduce.

    Nothing in general is wrong with deep sleep enabled. I mostly wonder what a typical case would be.

  12. Frulfump commented on Oct 29, 2026

    @Frulfump
  13. MichalPetryka commented on Oct 29, 2026

    @MichalPetryka
    Contributor

    14. Any change with RC3 since RC1 and 2 are out of support? I assume no but still.
    https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core

    RC3 was a vulnerability fix only afair.

  14. mgravell commented on Oct 29, 2026

    @mgravell
    ContributorAuthor

    @VSadov investigating now; also checking windows and linux separately (I have dual boot on the same hardware)

  15. mgravell commented on Oct 29, 2026

    @mgravell
    ContributorAuthor

    @VSadov good question. I've run the Redis-free repro natively on Windows, with idle states on and off. The machine is the same as for the Linux numbers in the repro: the box dual-boots, so it's the same Ryzen 9 7900X. The Linux run with C-states toggled will follow when I next boot into Linux.

    Short version: on Windows the regression doesn't reproduce, with deep idle on or off. Idle states do matter, but the runtime they hurt most is .NET 10, not .NET 11.

    Setup: the same pinned runtimes as before (10.0.12, 11.0.0-rc.1.26425.128, 11.0.0-rc.2.26504.105), with the server on cores 0-3 and the client on cores 6-11 (12 CPUs). Each figure is the median of 3 interleaved runs of 10 s, and the 3 runs agree within about 1-2%. "Idle off" is powercfg IDLEDISABLE=1.

    vs .NET 10 under the same idle setting

    cell RC1, idle on RC1, idle off RC2, idle on RC2, idle off
    1 caller +0.9% −3.2% +24.9% +7.6%
    64 callers −1.0% −1.6% +10.2% +0.8%
    64 callers, 5 µs work −0.4% −4.4% +19.7% +5.2%
    64 callers, 20 µs work −0.5% −0.2% +0.1% +0.1%
    64 callers, 78% hits completed in place, 1 µs work −0.5% −4.5% +16.8% +4.6%

    RC2 with SpuriousDispatchNoSpinThreshold=0 lands within about 1-8 points of default RC2 in every cell.

    64 callers, 5 µs work

    row idle ops/s busy (of 12) p99 µs
    .NET 10 on 689,489 7.22 141
    .NET 10 off 758,409 8.65 115
    RC1 on 686,416 7.40 147
    RC1 off 724,890 8.38 122
    RC2 on 825,327 10.86 141
    RC2 off 797,805 11.19 115

    For comparison, the same cell on Linux (deep idle at its default) was .NET 10 at 1,029,128 ops/s (11.56 busy) and RC2 at 667,782 (7.76 busy).

    What I take from this:

    • .NET 10 on Windows looks like .NET 11 on Linux. On Windows, .NET 10 keeps about 7 cores busy and RC2 about 11. On Linux it's the other way round. So whatever .NET 11 lost looks Linux-specific: something .NET 10 does on Linux (spinning, at a guess) that it never did on Windows.
    • Disabling idle states mostly helps the runtime that parks more. With idle off, .NET 10 gains 10% in the 5 µs cell and 29% at 1 caller. RC2 changes by +11% at 1 caller and −3% to −10% in the 64-caller cells, since it already keeps its cores busy. Wake-up latency is a real cost here, so I'd expect C-state configuration to shift how big the Linux regression looks. On this evidence it doesn't create it.
    • The 20 µs cell is CPU-bound on Windows (11.9 busy for every row), so idle states can't matter there.

    Caveats:

    • IDLEDISABLE turns off every idle state, C1 included; the processor polls. I couldn't test "C6 off, C1 on": Hyper-V is running on this box (for WSL/Docker), and IDLESTATEMAX has no effect under it. I set several values and the C1/C2/C3 residency counters didn't change, whereas IDLEDISABLE takes residency in every state to 0. On Linux I'll run both: cpupower idle-set -D 0 to match this run, and -D 2 for C6 only.
    • Windows runs natively over loopback, but the Linux numbers come from containers on host networking. Absolute latency-bound figures don't compare across the two (1 caller is about 20k ops/s on Windows against 55k on Linux); the "vs .NET 10" columns are the fair comparison.
    • The net11.0 app was compiled with a preview 7 SDK, with runtime async off, and rolled forward onto each RC runtime. Every result records the exact runtime build.
  16. mgravell commented on Oct 29, 2026

    @mgravell
    ContributorAuthor

    @VSadov here are the Linux C-state runs, completing the Windows half. Same machine (7900X, dual-boot), Pop!_OS, kernel 7.2.6, same pinned runtimes, server on cores 0-3,12-15 and client on 6-11,18-23. The cpuidle states here are POLL (0 µs exit latency), C1 (1 µs), ACPI C2 (18 µs, the deep CC6 state on Zen 4) and C3 (350 µs). Three full runs of the core grid, one per idle configuration: default (all states), C1 only (C2/C3 disabled), and POLL only (everything disabled — matching the Windows IDLEDISABLE run). States were toggled via /sys/devices/system/cpu/cpu*/cpuidle/stateN/disable, and I verified the usage counters of every disabled state stayed frozen across each run.

    Short version: idle states do not explain the Linux regression. The deficit vs .NET 10 is the same under all three configurations, including with every C-state disabled.

    RC2 vs .NET 10 under the same idle configuration

    cell default C1 only POLL only
    1 caller −5.3% −5.1% −4.2%
    64 callers +3.2% +5.6% +0.0%
    64 callers, 5 µs work −34.3% −34.0% −34.6%
    64 callers, 20 µs work −20.6% −19.8% −21.2%
    64 callers, 78% hits completed in place, 1 µs work −29.2% −29.0% −30.2%

    RC1 behaves the same way (5 µs cell: −42.4% / −40.2% / −38.4%).

    64 callers, 5 µs work

    row idle ops/s busy (of 12) p99 µs
    .NET 10 default 1,029,290 11.58 86
    .NET 10 C1 only 1,026,742 11.57 82
    .NET 10 POLL only 1,008,742 11.49 86
    RC2 default 676,674 7.87 344
    RC2 C1 only 677,539 7.81 344
    RC2 POLL only 659,785 7.73 344

    What I take from this:

    • Deep sleep isn't the variable here. .NET 10 keeps ~11.5 of 12 cores busy in the work cells under every idle configuration, so there's no parked-thread wake path for C-states to tax; and RC2 leaves the same ~4 cores idle whether a wake from idle costs 350 µs, 1 µs, or nothing at all (POLL). Whatever keeps .NET 11's workers from picking up the queue on Linux, it isn't wake-up latency.
    • Unlike Windows, disabling idle states never helps on Linux. On Windows, IDLEDISABLE bought .NET 10 +10% in the 5 µs cell and +29% at 1 caller. Here C1-only is a wash everywhere, and POLL-only costs ~18% at 1 caller for every runtime (.NET 10 55.8k → 45.6k ops/s, RC2 52.8k → 43.7k) — polling siblings presumably eat the boost/SMT budget.
    • The default run reproduces the 2026-10-15 numbers almost exactly (within ~1% in every cell, spreads mostly under 3%), so the original results stand as a default-idle baseline on a fresh boot two weeks later.

    Raw data, per-run idle-state records and the grid script are on the repro repo under results/core-20261029-*.

  17. Mercurial commented on Nov 16, 2026

    @Mercurial

    Another data point, in case it helps: a .NET 10-to-11 slowdown in a single process, with no sockets and one round trip in flight. This is a different workload from the original report; we have not established a common cause. We met it while moving a network protocol library to .NET 11; its receive path passes each message through a Pipe and a bounded channel.

    What we ran. Two tasks exchange one request and one reply at a time. The worker side executes 2,000 iterations of a multiply-add loop per request. The hand-off primitives are configured to schedule pending continuations asynchronously; awaits can still complete synchronously. Three variants of the same exchange: two bounded Channel<long> of capacity 1; TaskCompletionSource with RunContinuationsAsynchronously; two System.IO.Pipelines.Pipe with default options. No packages; the source is at the end.

    Setup. One net10.0 DLL, run with dotnet --fx-version on 10.0.15 and 11.0.0. Linux x64 (kernel 6.12), a cloud VM with 8 dedicated vCPUs (AMD EPYC, Fly.io performance-8x, 16 GB), steal 1.3%, workstation GC configured in the project, no pinning. 8 rounds; in each round every configuration runs in a fresh process (180 warm-up and 60 measured passes of 10,000 round trips), in rotated order. Figures are medians over the rounds. Ratios are taken per round against 10.0.15 and shown as median (lowest–highest). "Noise" is 10.0.15 run a second time in the same round.

    Hand-off ns per round trip, 10.0.15 → 11.0.0 11.0.0 / 10.0.15 Noise Voluntary context switches per round trip Request p50 ns Request p99 ns CPU per round trip, 11.0.0 / 10.0.15
    Channel 3709 → 4573 1.24 (1.04–1.35) 1.01 (0.98–1.06) 0.023 → 0.173 460 → 420 1810 → 5040 1.31
    TaskCompletionSource 3347 → 4054 1.18 (1.06–1.31) 1.00 (0.88–1.06) 0.015 → 0.139 265 → 180 795 → 4585 1.53
    Pipe 5481 → 6716 1.21 (1.08–1.56) 1.00 (0.93–1.26) 0.031 → 0.327 1070 → 1425 4775 → 7780 1.26

    “Request” is elapsed time from the timestamp taken just before publishing the request to the worker's timestamp immediately after its receive await returns, before CpuWork. For pipes this includes reading and decoding the 8-byte timestamp. Context switches are differences between sums of voluntary_ctxt_switches over /proc/self/task/*/status.

    The pipe comparison is noisier: its slowdown range overlaps the repeated-.NET-10 range.

    • Context switches. Median per-round ratios of voluntary context switches per round trip are 7.3× for channels, 10.8× for TaskCompletionSource, and 9.5× for pipes on 11.0.0 versus 10.0.15.
    • Request time. For channels and TaskCompletionSource the median-of-rounds Request p50 is lower on 11.0.0, but p90 goes from 0.7 to 1.8 µs and from 0.4 to 1.4 µs, and p99 from 1–2 µs to about 5 µs.
    • CPU. 11.0.0 does not use less CPU per round trip here. Across these three variants, median process CPU time divided by wall time corresponds to 3.5–4.7 busy cores out of 8, despite only one round trip being in flight.
    • DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 makes this shape slower for channels and TaskCompletionSource: 1.33 (1.13–1.36) and 1.36 (1.25–1.48) against 10.0.15. The pipe stays at 1.16 (1.05–1.34). CPU per round trip drops to 36–54% of .NET 10's, and median voluntary context switches rise to 0.49–0.76 per round trip.
    • No work per request. With the arithmetic removed, the channel variant is faster on 11.0.0: 0.80 (0.66–0.97), noise 0.94 (0.86–1.03).
    • Related PR. Reduce unnecessary spinning after empty thread-pool dispatches #136078 adds a condition for skipping the pre-wait spin after an empty dispatch: the last dispatch-progress timestamp is more than DispatchQuantumMs after the most recent worker request from outside the work-queue dispatcher. This worker-to-worker exchange may be relevant, but we have not built or measured that PR.
    Program.cs and HandoffRepro.csproj

    Save both files in an empty directory and build with a .NET 10 SDK: dotnet build HandoffRepro.csproj -c Release -o bin. With the requested runtime installed, run: dotnet --fx-version <version> bin/HandoffRepro.dll <channel|tcs|pipe> 2000 180 60 10000 out.json.

    // Asynchronous hand-off ping-pong between two logical tasks, using only .NET library types.
    // One round trip is outstanding at a time. Pending hand-off continuations use the thread pool;
    // an await can also complete synchronously. Built once for net10.0; the same DLL is
    // run on each runtime with `dotnet --fx-version <version>`.
    //
    // usage: HandoffRepro <channel|tcs|pipe> <work> <warmupPasses> <measuredPasses> <exchangesPerPass> <out.json>
    using System.Buffers;
    using System.Buffers.Binary;
    using System.Diagnostics;
    using System.IO.Pipelines;
    using System.Runtime.CompilerServices;
    using System.Text.Json;
    using System.Threading.Channels;
    
    string mode = args[0];
    int work = int.Parse(args[1]);
    int warmups = int.Parse(args[2]);
    int measured = int.Parse(args[3]);
    int count = int.Parse(args[4]);
    string output = args[5];
    
    long[] latency = new long[measured * count];
    double[] passNs = new double[measured];
    string loadStart = File.Exists("/proc/loadavg") ? File.ReadAllText("/proc/loadavg").Trim() : "";
    
    for (int pass = 0; pass < warmups; pass++) await RunPass(mode, count, work, null, 0);
    
    Process self = Process.GetCurrentProcess();
    self.Refresh();
    TimeSpan cpuTotal0 = self.TotalProcessorTime, cpuUser0 = self.UserProcessorTime;
    long switches0 = VoluntarySwitches();
    long completed0 = ThreadPool.CompletedWorkItemCount;
    long wall0 = Stopwatch.GetTimestamp();
    for (int pass = 0; pass < measured; pass++)
        passNs[pass] = await RunPass(mode, count, work, latency, pass * count);
    long wall1 = Stopwatch.GetTimestamp();
    self.Refresh();
    TimeSpan cpuTotal1 = self.TotalProcessorTime, cpuUser1 = self.UserProcessorTime;
    long switches1 = VoluntarySwitches();
    long completed1 = ThreadPool.CompletedWorkItemCount;
    
    double exchanges = (double)measured * count;
    Array.Sort(latency);
    Array.Sort(passNs);
    double Q(double p) => ToNs(latency[(int)((latency.Length - 1) * p)]);
    var result = new
    {
        runtime = Environment.Version.ToString(),
        mode, work, warmups, measured, count,
        processorCount = Environment.ProcessorCount,
        spuriousDispatchNoSpinThreshold = Environment.GetEnvironmentVariable("DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold"),
        unfairSemaphoreSpinLimit = Environment.GetEnvironmentVariable("DOTNET_ThreadPool_UnfairSemaphoreSpinLimit"),
        nsPerRoundTrip = ToNs(wall1 - wall0) / exchanges,
        medianPassNsPerRoundTrip = passNs[measured / 2],
        cpuNsPerRoundTrip = (cpuTotal1 - cpuTotal0).TotalNanoseconds / exchanges,
        userCpuNsPerRoundTrip = (cpuUser1 - cpuUser0).TotalNanoseconds / exchanges,
        busyCores = (cpuTotal1 - cpuTotal0).TotalSeconds / Stopwatch.GetElapsedTime(wall0, wall1).TotalSeconds,
        voluntarySwitchesPerRoundTrip = (switches1 - switches0) / exchanges,
        workItemsPerRoundTrip = (completed1 - completed0) / exchanges,
        requestNs = new { mean = latency.Average(v => ToNs(v)), p50 = Q(.5), p90 = Q(.9), p99 = Q(.99), p999 = Q(.999) },
        poolThreads = ThreadPool.ThreadCount,
        loadStart,
        loadEnd = File.Exists("/proc/loadavg") ? File.ReadAllText("/proc/loadavg").Trim() : "",
    };
    File.WriteAllText(output, JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
    return 0;
    
    static double ToNs(long ticks) => ticks * (1e9 / Stopwatch.Frequency);
    
    static long VoluntarySwitches()
    {
        long total = 0;
        try
        {
            foreach (string dir in Directory.EnumerateDirectories("/proc/self/task"))
                foreach (string line in File.ReadLines(Path.Combine(dir, "status")))
                    if (line.StartsWith("voluntary_ctxt_switches:", StringComparison.Ordinal))
                        total += long.Parse(line.AsSpan(24).Trim());
        }
        catch (IOException) { }
        return total;
    }
    
    static Task<double> RunPass(string mode, int count, int work, long[]? latency, int offset) => mode switch
    {
        "channel" => Handoff.Channels(count, work, latency, offset),
        "tcs" => Handoff.CompletionSources(count, work, latency, offset),
        "pipe" => Handoff.Pipes(count, work, latency, offset),
        _ => throw new ArgumentException(mode),
    };
    
    public static class Handoff
    {
        private static double ToNs(long ticks) => ticks * (1e9 / Stopwatch.Frequency);
    
        // Two bounded channels of capacity 1, default (asynchronous) continuations.
        public static async Task<double> Channels(int count, int work, long[]? latency, int offset)
        {
            BoundedChannelOptions options = new(1) { SingleReader = true, SingleWriter = true };
            Channel<long> request = Channel.CreateBounded<long>(options);
            Channel<long> reply = Channel.CreateBounded<long>(options);
            Task<long> worker = Task.Run(async () =>
            {
                long checksum = 0;
                for (int i = 0; i < count; i++)
                {
                    long stamp = await request.Reader.ReadAsync().ConfigureAwait(false);
                    if (latency != null) latency[offset + i] = Stopwatch.GetTimestamp() - stamp;
                    checksum ^= CpuWork(work, i);
                    await reply.Writer.WriteAsync(checksum).ConfigureAwait(false);
                }
                return checksum;
            });
            long start = Stopwatch.GetTimestamp();
            for (int i = 0; i < count; i++)
            {
                await request.Writer.WriteAsync(Stopwatch.GetTimestamp()).ConfigureAwait(false);
                await reply.Reader.ReadAsync().ConfigureAwait(false);
            }
            long end = Stopwatch.GetTimestamp();
            await worker.ConfigureAwait(false);
            return ToNs(end - start) / count;
        }
    
        // TaskCompletionSource with RunContinuationsAsynchronously in both directions.
        public static async Task<double> CompletionSources(int count, int work, long[]? latency, int offset)
        {
            const TaskCreationOptions Async = TaskCreationOptions.RunContinuationsAsynchronously;
            TaskCompletionSource<long> request = new(Async);
            TaskCompletionSource<long> reply = new(Async);
            TaskCompletionSource started = new(Async);
            Task<long> worker = Task.Run(async () =>
            {
                long checksum = 0;
                started.SetResult();
                for (int i = 0; i < count; i++)
                {
                    long stamp = await request.Task.ConfigureAwait(false);
                    if (latency != null) latency[offset + i] = Stopwatch.GetTimestamp() - stamp;
                    checksum ^= CpuWork(work, i);
                    TaskCompletionSource<long> current = reply;
                    request = new(Async);          // published before the requester is released
                    current.SetResult(checksum);
                }
                return checksum;
            });
            await started.Task.ConfigureAwait(false);
            long start = Stopwatch.GetTimestamp();
            for (int i = 0; i < count; i++)
            {
                TaskCompletionSource<long> current = reply;
                request.SetResult(Stopwatch.GetTimestamp());
                await current.Task.ConfigureAwait(false);
                reply = new(Async);                // the worker reads it only after the next request
            }
            long end = Stopwatch.GetTimestamp();
            await worker.ConfigureAwait(false);
            return ToNs(end - start) / count;
        }
    
        // Two System.IO.Pipelines pipes with default options (thread-pool schedulers), 8-byte messages.
        public static async Task<double> Pipes(int count, int work, long[]? latency, int offset)
        {
            Pipe request = new(), reply = new();
            Task<long> worker = Task.Run(async () =>
            {
                long checksum = 0;
                for (int i = 0; i < count; i++)
                {
                    long stamp = await ReadInt64(request.Reader).ConfigureAwait(false);
                    if (latency != null) latency[offset + i] = Stopwatch.GetTimestamp() - stamp;
                    checksum ^= CpuWork(work, i);
                    await WriteInt64(reply.Writer, checksum).ConfigureAwait(false);
                }
                return checksum;
            });
            long start = Stopwatch.GetTimestamp();
            for (int i = 0; i < count; i++)
            {
                await WriteInt64(request.Writer, Stopwatch.GetTimestamp()).ConfigureAwait(false);
                await ReadInt64(reply.Reader).ConfigureAwait(false);
            }
            long end = Stopwatch.GetTimestamp();
            await worker.ConfigureAwait(false);
            return ToNs(end - start) / count;
        }
    
        private static ValueTask<FlushResult> WriteInt64(PipeWriter writer, long value)
        {
            BinaryPrimitives.WriteInt64LittleEndian(writer.GetSpan(8), value);
            writer.Advance(8);
            return writer.FlushAsync();
        }
    
        private static async ValueTask<long> ReadInt64(PipeReader reader)
        {
            while (true)
            {
                ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
                ReadOnlySequence<byte> buffer = result.Buffer;
                if (buffer.Length >= 8)
                {
                    Span<byte> bytes = stackalloc byte[8];
                    buffer.Slice(0, 8).CopyTo(bytes);
                    long value = BinaryPrimitives.ReadInt64LittleEndian(bytes);
                    reader.AdvanceTo(buffer.GetPosition(8));
                    return value;
                }
                reader.AdvanceTo(buffer.Start, buffer.End);
            }
        }
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static long CpuWork(int iterations, long state)
        {
            for (int i = 0; i < iterations; i++) state = unchecked(state * 1664525 + 1013904223);
            return state;
        }
    }
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <UseAppHost>false</UseAppHost>
        <ServerGarbageCollection>false</ServerGarbageCollection>
        <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
        <TieredPGO>true</TieredPGO>
      </PropertyGroup>
    </Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions