You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Runtime async has major perf regression since .NET 11 RC2 #135738
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.
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.
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.
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.
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).
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.
Bound the CPU spent on spins that find no work, in I/O-driven workloads.
Here that spinning costs 50 µs per query at 4 workers and 30 at 16 (default against threshold 0), and buys no throughput (point 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.
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.
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.
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.
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.
Activity
dotnet-policy-service commentedon Oct 14, 2026
Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.
hez2010 commentedon Oct 14, 2026
Bisected to #132908 (and #132765).
Setting
DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0restore the perf for me. I guess the heuristics need further tuning.Without setting
DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0we are spending a lot of time inSystem.Threading.LowLevelLifoSemaphore.WaitSlow.cc: @VSadov
hez2010 commentedon Oct 15, 2026
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.
I think this should be simple enough to be put in .NET 11.
/cc: @VSadov
hez2010 commentedon Oct 15, 2026
Benchmark of the above patch against RC1 and RC2:
Async benchmark:
#135855 Multiplexed TCP: 64 callers, one connection, 5 µs work.
#132765 WebSocket workload: 100 connections, 1,000-byte echo, compression disabled.
Same #132765 WebSocket workload with four connections:
coderb commentedon Nov 12, 2026
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.15andv11.0.0tags.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:
SpuriousDispatchNoSpinThreshold=0UnfairSemaphoreSpinLimit=0UnfairSemaphoreSpinLimit=0On 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.
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.
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).
CPU tracks the semaphore spin limit. On .NET 11 (Linux, 4 workers) the total CPU per query at each
UnfairSemaphoreSpinLimitwas: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_UnfairSemaphoreSpinLimitas hex (AppContextConfigHelper.csline 255,NumberStyles.HexNumber), so=1024means 4132 and=70means 112. The limits above are the values the runtime actually used.The mechanism, from the source
LowLevelLifoSemaphore.WaitSlowspins up toDefaultSemaphoreSpinCountLimit = 1024units (LowLevelLifoSemaphore.csline 23). It's a pureBackoff.Exponential/Thread.SpinWaitloop with no yield (line 116), "about 35 microseconds" by its own comment (line 22). It adds a 4 µs wake cooldown (line 26).SemaphoreSpinCountDefault = 70steps (PortableThreadPool.WorkerThread.csline 18), doubled on Unix (LowLevelLifoSemaphore.csline 99). AfterSpinSleep0Threshold = 10steps (line 22) it alternatedSpinWaitwithSleep(0)(line 105, throughLowLevelSpinWaiter). That is the kernel time .NET 10 shows and .NET 11 doesn't.TryRemoveWorkingWorker,PortableThreadPool.WorkerThread.csline 188) before it waits on the semaphore (line 127). So spinners are invisible tonumProcessingWork, as noted above.numProcessingWork > SpuriousDispatchNoSpinThreshold(line 193). The threshold defaults toProcessorCount * 2 / 3(line 45): 16 on these machines, which 4 or 16 workers never exceed.SpuriousDispatchNoSpinThreshold=0recovers most of the cost but not all of it: 31.8 against 21.4 µs per query with the semaphore spin off.SocketAsyncEngine.Unix.csline 308);PortableThreadPool.IO.Windows.csline 273);TimerQueue.Portable.csline 128, throughEnqueueAtHighPriority, which callsEnsureWorkerRequestedatThreadPoolWorkQueue.csline 688).What a fix has to do
Each requirement comes with the evidence for it.
DispatchQuantumMs).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.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.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
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.coderb commentedon Nov 12, 2026
@stephentoub could you please review this issue, it is a show stopper for us.