DI: (opt) ILEmit resolvers re-take the scope lock for nested scoped services and use interface dispatch on the scope cache
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 12/100
- issue の種類
- リファクタリング
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- csharp
- 領域
- performance
調査の方向性
Start in src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs: read GenerateMethodBody for the Monitor.Enter/Exit prologue and the TryGetValue/Add callvirt sites, then ILEmitResolverBuilderRuntimeContext and ExpressionResolverBuilder where the shared MethodInfos are consumed. The proposed change is three independent pieces — the ScopeLockHeld context flag, direct Dictionary<ServiceCacheKey, object?> calls, and ldnull for a null ServiceKey — and the issue suggests landing the latter two separately. Done means existing DI tests under src/libraries/Microsoft.Extensions.DependencyInjection/tests pass plus a benchmark showing the recursive lock gone for nested scoped graphs.
索引モデルが issue の本文から書いたものです。
説明
Problem
In OrchardCore on Cobalt 200, Microsoft.Extensions.DependencyInjection machinery (excluding the services' own constructors) is about 11.7% of CPU:
| Symbol | % of cycles |
|---|---|
Dictionary<ServiceCacheKey, object>.TryGetValue/Add/Resize |
~2.9% |
dynamicClass::ResolveService (bodies) |
2.0% |
Monitor.Exit |
1.57% |
Monitor.Enter |
1.01% |
ObjectHeader.TryAcquireUncommon (recursive thin-lock path) |
0.79% |
CastHelpers.StelemRef_Helper (IEnumerable arrays) |
0.30% |
VSD dispatch stubs called from ResolveService |
0.19% |
Three inefficiencies in the code emitted by ILEmitResolverBuilder for scope-cached call sites:
- Recursive scope locking. Every scoped resolver does
Monitor.Enter(scope.Sync)and builds the service while holding the lock. A scoped dependency of a scoped service is resolved by calling the dependency'sDynamicMethod, which takes the same lock again (a recursive thin lock: CAS inTryAcquireUncommonplus CAS inExit). Deep scoped graphs re-enter the lock once per level.CallSiteRuntimeResolveralready avoids this withRuntimeResolverLock/AcquiredLocks; the ILEmit path doesn't. On arm64 each of these CASes is acasal, andMonitor.Exitspends 83% of its samples on it. - Interface dispatch on the cache. The emitted code calls
TryGetValue/AddthroughIDictionary<ServiceCacheKey, object>, so each scoped resolve does two VSD interface calls.ResolvedServicesis always aDictionary<ServiceCacheKey, object?>, so the calls can be direct (andTryGetValuegets inlined into the dynamic method). - Null service key loaded from the constants array. The cache key is built with
AddConstant(id.ServiceKey)even when the key isnull(the common, non-keyed case). That's a dependent load chain (context ->Constantsarray -> bounds check -> element) on every resolve; in the hottestResolveServiceinstances ~40% of samples sat on that length load/bounds check (some of it likely skid from the prologue).
Proposal
- Track at emit time whether code runs under the scope lock (
ILEmitResolverBuilderContext.InScopeLock, set while emitting the creation of a scope-cached service). Each scope-cachedGeneratedMethodgets a second runtime context instance that is identical except forScopeLockHeld = true. Nested calls emitted under the lock pass that context, and the emitted prologue skipsMonitor.Enterwhencontext.ScopeLockHeldis set. That's one field load and a branch, no extra call, no extra dynamic methods, and the same "take the lock once per resolution chain" semantics asCallSiteRuntimeResolver. Nested calls always pass the samescopeargument (ldarg.1), so the caller does hold that scope's lock. - Use
Dictionary<ServiceCacheKey, object?>.TryGetValue/Addviacall(also for the expression-tree builder, which shares theMethodInfos). - Emit
ldnullwhenServiceKeyis null.
An earlier variant used Monitor.IsEntered(sync) instead of the context flag; it was slightly slower for non-nested resolution because of the extra call, so I went with the emit-time approach.
Invariants the lock elision relies on:
- Nested scoped resolvers are only reached through direct, synchronous emitted calls that forward the caller's own
ldarg.1, so the callee's scope is exactly the scope whose lock the caller holds. - The
IsRootScopebranch runs before the skip, and the delegate returned byBuild(used byServiceProvider.GetService) stays bound to the unlocked context. finallyonly callsMonitor.Exitwhen the current invocation took the lock.- Singleton dependencies are resolved at emit time (
VisitRootCache), and factories re-enter through the provider, which uses the unlocked context. So factories keep today's (recursive) locking.
For (2), changing only the opcode isn't enough: the receiver must be typed as Dictionary<ServiceCacheKey, object> everywhere the shared MethodInfos are used, i.e. resolvedServicesLocal in ILEmitResolverBuilder.GenerateMethodBody and the ResolvedServices ParameterExpression in ExpressionResolverBuilder (otherwise Expression.Call throws). (2) and (3) are independent of (1) and could go in a separate, trivial PR.
Core of the change:
private sealed class ILEmitResolverBuilderRuntimeContext
{
public object?[]? Constants;
public Func<IServiceProvider, object>[]? Factories;
+ // True for the context passed by resolvers that already hold the scope lock.
+ public bool ScopeLockHeld;
}
...
- AddConstant(argument, generatedMethod.Context);
+ // When called under the scope lock (from another scoped resolver), let the callee skip taking it again.
+ AddConstant(argument, argument.InScopeLock ? generatedMethod.ScopeLockHeldContext : generatedMethod.Context);
...
+ // Skip Monitor.Enter if the caller already holds the scope lock (nested scoped resolution)
+ context.Generator.Emit(OpCodes.Ldarg_0);
+ context.Generator.Emit(OpCodes.Ldfld, ScopeLockHeldField);
+ context.Generator.Emit(OpCodes.Brtrue, lockHeldLabel);
...Monitor.Enter(sync, ref lockTaken)...
+ context.Generator.MarkLabel(lockHeldLabel);
...
- context.Generator.Emit(OpCodes.Callvirt, ServiceLookupHelpers.TryGetValueMethodInfo);
+ context.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.TryGetValueMethodInfo);
...
+ context.InScopeLock = true;
VisitCallSiteMain(callSite, context);
+ context.InScopeLock = false;
Measurements (Cobalt 200, linux-arm64)
Microbenchmark: one scope per iteration, resolving a root scoped service with a 6-level scoped dependency graph (plus a disposable and an IEnumerable<IDep>), then 4 cached lookups. "Flat" resolves 5 independent scoped services twice each.
public sealed class D0 : IDep { }
public sealed class D1 : IDep { public D1(D0 d) { } }
public sealed class D2 : IDep { public D2(D0 a, D1 b) { } }
public sealed class D3 : IDep { public D3(D1 a, D2 b) { } }
public sealed class D4 : IDep { public D4(D2 a, D3 b, D0 c) { } }
public sealed class D5 : IDep { public D5(D4 a, D3 b) { } }
public sealed class Disp : IDisposable { public Disp(D5 d) { } public void Dispose() { } }
public sealed class Root { public Root(D5 a, D4 b, Disp c, IEnumerable<IDep> all) { } }
static void Run(IServiceProvider sp) {
using var scope = sp.CreateScope();
var p = scope.ServiceProvider;
p.GetService(typeof(Root));
p.GetService(typeof(D3)); p.GetService(typeof(D4)); p.GetService(typeof(D5)); p.GetService(typeof(D1));
}
| Baseline (main) | Patched | ||
|---|---|---|---|
| nested | 0.80 M scopes/s | 1.10 M scopes/s | +37% |
| flat | ~1.94 M scopes/s | ~1.98 M scopes/s | neutral |
OrchardCore /about (6 runs each, 3 processes, rotated order): +1.9% RPS (27,282 -> 27,803). In the profile TryAcquireUncommon disappears and Monitor.Exit drops from 1.57% to 0.90%.
Notes
CaptureDisposablestill doeslock (Sync)while the scope lock is already held (recursive), but it was only ~0.09% here.- The remaining DI cost is mostly memory latency in
Dictionary<ServiceCacheKey, object>.FindValue(the per-request scope cache) and the non-nestedMonitor.Enter/Exitpair.
[!NOTE]
This issue was drafted with the help of GitHub Copilot.
- 主要言語
- C#
- スター
- 18.5k
- フォーク
- 5.8k
- 平均マージ
- 2日 18時間
- マージ済み PR(30日)
- 588
環境構築
このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
dotnet/runtime のほかの issue
-
area-CodeGen-coreclr untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
dotnet/runtime#138181 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
area-System.Collections untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
dotnet/runtime#138090 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
area-System.Text.Json untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
dotnet/runtime#138089 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
area-Setup untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
dotnet/runtime#137376 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
area-System.Memory untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
dotnet/runtime#137334 · コメント 4 件 ·
メンテナーはふだん 1 日以内に返信
似ている issue
-
Add `net10.0`オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 66/100
dotnet-outdated/dotnet-outdated#871 ·
メンテナーはふだん 1 日以内に返信
-
triage/untriaged
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
unoplatform/uno#26676 ·
メンテナーはふだん 1 日以内に返信
-
.NET bug
難易度 2/5 1〜3時間 初心者へのやさしさ 84/100
メンテナーはふだん 1 日以内に返信
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
jhaizhou-ops/S2Arm#2177 · コメント 3 件 ·
メンテナーはふだん 1 日以内に返信