diff --git a/docs/event-infrastructure.md b/docs/event-infrastructure.md index b50572b77..0f07b7130 100644 --- a/docs/event-infrastructure.md +++ b/docs/event-infrastructure.md @@ -427,18 +427,7 @@ For **static events**, there's no object instance. Instead, the generated code u ```csharp // Generated in the projected class -private static WindowsRuntimeObjectReference __IStaticsType -{ - get - { - var ___IStaticsType = field; - if (___IStaticsType != null && ___IStaticsType.IsInCurrentContext) - { - return ___IStaticsType; - } - return field = WindowsRuntimeObjectReference.GetActivationFactory("TypeName", iid); - } -} +private static WindowsRuntimeObjectReference __IStaticsType => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "TypeName", iid); ``` And the event accessors pass this factory reference as the `thisObject`: @@ -473,10 +462,10 @@ public static EventHandlerEventSource SomeStaticEvent( ### The Activation Factory Cache -The static property `__IStaticsType` uses a **semi-cached** pattern: +The static property `__IStaticsType` uses a **semi-cached** pattern (implemented by `WindowsRuntimeObjectReference.GetActivationFactory(ref ...)`): -1. On first access: calls `WindowsRuntimeObjectReference.GetActivationFactory(...)` and stores the result. -2. On subsequent accesses: checks `IsInCurrentContext`. If the current COM context matches the one where the factory was created, returns the cached value. +1. On first access: calls `WindowsRuntimeObjectReference.GetActivationFactory(...)` and stores the result in the backing field. +2. On subsequent accesses: returns the cached value, as long as it can be used from the current COM context (free-threaded factories always can, context-aware ones are checked with `IsInCurrentContext`). 3. If the context has changed (e.g., thread apartment transition): **re-fetches** the activation factory and **overwrites** the cached field. This means the cached `WindowsRuntimeObjectReference` for the activation factory can be replaced at any time if there's a context switch. @@ -492,7 +481,7 @@ private protected sealed override bool DerivedIsInCurrentContext() } ``` -When this returns `false`, the generated code discards the cached activation factory and creates a fresh one. This is where the concern about static events arises. +When this returns `false`, the cached activation factory is discarded and a fresh one is created. This is where the concern about static events arises. ### Static Event Lifecycle Analysis @@ -520,11 +509,11 @@ MyRuntimeClass.StaticEvent += MyHandler; - Code on a different thread (different COM apartment) accesses `__IStaticsType`. - `IsInCurrentContext` returns `false` for `A`. -- A new activation factory `B` is fetched and stored in `field`, **replacing** `A`. +- A new activation factory `B` is fetched and stored in the static field, **replacing** `A`. **Step 3: What happens to `A`?** -- `A` is no longer referenced by the static `field` (it was overwritten by `B`). +- `A` is no longer referenced by the static field (it was overwritten by `B`). - The `ConditionalWeakTable` used `A` as a **weak key**. Once `A` has no strong references, it becomes eligible for GC. - When `A` is collected, the `ConditionalWeakTable` automatically removes the entry, which means the `EventSource` is also eligible for GC. - The `EventSource` held a `WeakReference` to the `EventSourceState`. @@ -617,6 +606,6 @@ In short, changing the key alone is not the whole answer: it must be paired with The root cause is that the activation factory object reference is an **unstable key** that can be replaced on context switches, yet it's also the key that keeps the `EventSource` (and indirectly the `EventSourceState` with its token) reachable. The fix must ensure the old activation factory (and therefore the old event source / state) remains reachable while subscriptions are active. This is safe because `EventSource` already handles cross-context calls correctly — `WindowsRuntimeObjectReference.AsValue()` / `GetThisPtrWithContextUnsafe()` will marshal to the correct context via COM context callbacks when needed. -**Keep a strong reference to the activation factory while subscriptions are active** — The `EventSourceState` (or the `EventSource`) could hold a strong reference back to the activation factory object reference that was used during subscription. Because `ConditionalWeakTable` uses weak keys, keeping a strong reference to the old activation factory prevents it from being collected, which in turn prevents the table entry (and the `EventSource`) from being evicted. When the activation factory property is later accessed from a different context, it will produce a new `WindowsRuntimeObjectReference` and cache it in `field`, but the old one remains alive (held by the state). The `ConditionalWeakTable` lookup from the new context won't find a match (different key identity), but the **`EventSourceCache`** (keyed by native pointer, not object identity) can reconnect a new `EventSource` to the surviving `EventSourceState` — provided the native object supports `IWeakReferenceSource`. If it doesn't (which is the common case for static factories), an additional mechanism would be needed — for instance, having the generated code also maintain a direct strong reference to the `EventSource` in a static field while subscriptions are active, bypassing the `ConditionalWeakTable` for the reconnection step. +**Keep a strong reference to the activation factory while subscriptions are active** — The `EventSourceState` (or the `EventSource`) could hold a strong reference back to the activation factory object reference that was used during subscription. Because `ConditionalWeakTable` uses weak keys, keeping a strong reference to the old activation factory prevents it from being collected, which in turn prevents the table entry (and the `EventSource`) from being evicted. When the activation factory property is later accessed from a different context, it will produce a new `WindowsRuntimeObjectReference` and cache it in the static field, but the old one remains alive (held by the state). The `ConditionalWeakTable` lookup from the new context won't find a match (different key identity), but the **`EventSourceCache`** (keyed by native pointer, not object identity) can reconnect a new `EventSource` to the surviving `EventSourceState` — provided the native object supports `IWeakReferenceSource`. If it doesn't (which is the common case for static factories), an additional mechanism would be needed — for instance, having the generated code also maintain a direct strong reference to the `EventSource` in a static field while subscriptions are active, bypassing the `ConditionalWeakTable` for the reconnection step. This approach is the most targeted fix: it only keeps the factory alive for the duration of active subscriptions, the existing `EventSource` correctly handles cross-context marshalling for any native calls, and it naturally cleans up when all handlers are removed (the strong reference is released, the activation factory becomes collectible, and the `ConditionalWeakTable` entry is evicted). diff --git a/docs/runtime-class-projections.md b/docs/runtime-class-projections.md index d3cca609d..ed9f7a7ec 100644 --- a/docs/runtime-class-projections.md +++ b/docs/runtime-class-projections.md @@ -20,6 +20,10 @@ For sealed runtime classes like `WinRTClass`, the generated constructors are rel ```csharp public sealed class WinRTClass : WindowsRuntimeObject { + // Cached activation factory (resolved and managed by 'WindowsRuntimeObjectReference') + private static WindowsRuntimeObjectReference _objRef_global__MyLib_WinRTClass => + WindowsRuntimeObjectReference.GetActivationFactory(ref field, "MyLib.WinRTClass"); + // Default constructor - uses activation factory directly public WinRTClass() : base(_objRef_global__MyLib_WinRTClass, in IID_MyLib_WinRTClass) @@ -47,6 +51,8 @@ public sealed class WinRTClass : WindowsRuntimeObject } ``` +The `_objRef_*` property for the activation factory is a one-liner over its own backing field (the C# `field` keyword): `WindowsRuntimeObjectReference.GetActivationFactory(ref field, ...)` resolves the activation factory on first use, and again whenever the cached one can't be used from the current COM context. The same pattern is used for the activation factories of static and factory interfaces (including composable factories), which also take the IID of the interface to resolve. + In this example, we have a parameterless constructor and one with a `string` parameter. Any additional constructors taking parameters would use the same callback pattern (see details below), where the parameters are passed via a `ReadOnlySpan`. > [!NOTE] diff --git a/src/WinRT.Projection.Writer/Factories/ClassFactory.cs b/src/WinRT.Projection.Writer/Factories/ClassFactory.cs index 709fe3cd4..bbc80323e 100644 --- a/src/WinRT.Projection.Writer/Factories/ClassFactory.cs +++ b/src/WinRT.Projection.Writer/Factories/ClassFactory.cs @@ -494,8 +494,8 @@ public static event {{eventType}} {{evtName}} } /// - /// Emits the static lazy objref property for a static factory interface (mirrors truth's - /// pattern: lazy WindowsRuntimeObjectReference.GetActivationFactory(...)). + /// Emits the static objref property for an activation factory interface (ie. a [Static], [Activatable], + /// or [Composable] factory interface), see . /// internal static void WriteStaticFactoryObjRef(IndentedTextWriter writer, ProjectionEmitContext context, TypeDefinition staticIface, string runtimeClassFullName, string objRefName) { @@ -507,24 +507,33 @@ internal static void WriteStaticFactoryObjRef(IndentedTextWriter writer, Project return; } - writer.WriteLine(); + WriteActivationFactoryObjRef(writer, runtimeClassFullName, objRefName, ObjRefNameGenerator.WriteIidExpression(context, staticIface)); + } - IndentedTextWriterCallback iid = ObjRefNameGenerator.WriteIidExpression(context, staticIface); + /// + /// Emits the static objref property for an activation factory of a given runtime class (using the property backing field to cache it). + /// + /// The instance to write to. + /// The full name of the runtime class to get the activation factory for. + /// The name of the objref property to emit (ie. _objRef_*). + /// The IID expression for the activation factory interface, or for the default IActivationFactory interface. + /// + /// This method should not be called for reference projections (where the objref is omitted). + /// + internal static void WriteActivationFactoryObjRef(IndentedTextWriter writer, string runtimeClassFullName, string objRefName, IndentedTextWriterCallback? iid) + { + writer.WriteLine(); - writer.WriteLine(isMultiline: true, $$""" - private static WindowsRuntimeObjectReference {{objRefName}} - { - get - { - var __{{objRefName}} = field; - if (__{{objRefName}} != null && __{{objRefName}}.IsInCurrentContext) - { - return __{{objRefName}}; - } - return field = WindowsRuntimeObjectReference.GetActivationFactory("{{runtimeClassFullName}}", {{iid}}); - } - } - """); + // The cached activation factory (the property backing field) is managed by 'WindowsRuntimeObjectReference', which also takes + // care of resolving a new activation factory when the cached one can't be used (ie. when it is accessed from a different context). + if (iid is null) + { + writer.WriteLine($"""private static WindowsRuntimeObjectReference {objRefName} => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "{runtimeClassFullName}");"""); + } + else + { + writer.WriteLine($"""private static WindowsRuntimeObjectReference {objRefName} => WindowsRuntimeObjectReference.GetActivationFactory(ref field, "{runtimeClassFullName}", {iid});"""); + } } /// diff --git a/src/WinRT.Projection.Writer/Factories/ConstructorFactory.AttributedTypes.cs b/src/WinRT.Projection.Writer/Factories/ConstructorFactory.AttributedTypes.cs index b6ee41827..924ee7ff1 100644 --- a/src/WinRT.Projection.Writer/Factories/ConstructorFactory.AttributedTypes.cs +++ b/src/WinRT.Projection.Writer/Factories/ConstructorFactory.AttributedTypes.cs @@ -42,22 +42,7 @@ public static void WriteAttributedTypes(IndentedTextWriter writer, ProjectionEmi { string fullName = classType.FullName ?? string.Empty; string objRefName = "_objRef_" + IidExpressionGenerator.EscapeTypeNameForIdentifier(GlobalPrefix + fullName, stripGlobal: true); - writer.WriteLine(); - writer.Write($"private static WindowsRuntimeObjectReference {objRefName}"); - writer.WriteLine(); - writer.WriteLine(isMultiline: true, $$""" - { - get - { - var __{{objRefName}} = field; - if (__{{objRefName}} != null && __{{objRefName}}.IsInCurrentContext) - { - return __{{objRefName}}; - } - return field = WindowsRuntimeObjectReference.GetActivationFactory("{{fullName}}"); - } - } - """); + ClassFactory.WriteActivationFactoryObjRef(writer, fullName, objRefName, iid: null); } // A class can be activated through several composable factories (e.g. one per contract version), but the diff --git a/src/WinRT.Runtime/InteropServices/ObjectReference/WindowsRuntimeObjectReference.Activation.cs b/src/WinRT.Runtime/InteropServices/ObjectReference/WindowsRuntimeObjectReference.Activation.cs index 66bb08400..8a4adb190 100644 --- a/src/WinRT.Runtime/InteropServices/ObjectReference/WindowsRuntimeObjectReference.Activation.cs +++ b/src/WinRT.Runtime/InteropServices/ObjectReference/WindowsRuntimeObjectReference.Activation.cs @@ -3,6 +3,8 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading; #pragma warning disable CS1573 @@ -30,6 +32,49 @@ public static WindowsRuntimeObjectReference GetActivationFactory(string runtimeC return AttachUnsafe(ref activationFactory, in iid)!; } + /// + /// Gets a cached activation factory for the specified Windows Runtime type, resolving a new one if needed. + /// + /// The location of the cached activation factory (initially ), which is updated whenever a new activation factory is resolved. + /// The IID of the interface pointer (from the resolved activation factory) to wrap in the returned object reference. + /// A instance wrapping an instance of the activation factory for the specified Windows Runtime type. + /// + /// + /// The cached activation factory is reused as long as it can be used from the current context. In all other cases, a new activation + /// factory is resolved and stored in . + /// + /// + /// If multiple threads resolve a new activation factory concurrently, the last one to be stored wins (all resolved instances are valid). + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static WindowsRuntimeObjectReference GetActivationFactory( + ref WindowsRuntimeObjectReference? location, + string runtimeClassName, + in Guid iid) + { + // Fast path for free-threaded activation factories (ie. almost always). Context-aware activation factories always go through the + // slow path, which also checks whether they're in the current context. We intentionally don't check 'IsInCurrentContext' here: it + // calls into a virtual method, and the guarded devirtualization for it would inline a copy of that check for each context-aware + // type (plus the 'CoGetContextToken' call) into every getter, bloating binary size. The slot is read with a volatile operation, + // as it can be updated concurrently by other threads. + return Volatile.Read(ref location) is { IsFreeThreaded: true } activationFactory + ? activationFactory + : GetOrResolveActivationFactory(ref location, runtimeClassName, in iid); + } + + /// + /// + /// This overload resolves the default IActivationFactory interface (see ). + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static WindowsRuntimeObjectReference GetActivationFactory(ref WindowsRuntimeObjectReference? location, string runtimeClassName) + { + // A 'null' IID means that the default 'IActivationFactory' interface should be resolved (same as for 'WindowsRuntimeActivationFactory') + return GetActivationFactory(ref location, runtimeClassName, in Unsafe.NullRef()); + } + /// A instance wrapping an instance of the activation factory for the specified Windows Runtime type, if successfully retrieved. /// public static bool TryGetActivationFactory(string runtimeClassName, [NotNullWhen(true)] out WindowsRuntimeObjectReference? activationFactory) @@ -61,4 +106,31 @@ public static bool TryGetActivationFactory(string runtimeClassName, in Guid iid, return true; } + + /// + /// Gets the cached activation factory if it can be reused, or resolves (and caches) a new one otherwise. + /// + /// The IID of the interface pointer to resolve, or a reference for the default IActivationFactory interface. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static WindowsRuntimeObjectReference GetOrResolveActivationFactory( + ref WindowsRuntimeObjectReference? location, + string runtimeClassName, + in Guid iid) + { + // The fast path only accepts free-threaded activation factories, so this is where cached context-aware ones are validated. + // They can be reused if they're in the current context. Without this check, they'd be resolved on every access. + if (Volatile.Read(ref location) is { IsInCurrentContext: true } cachedActivationFactory) + { + return cachedActivationFactory; + } + + WindowsRuntimeObjectReference activationFactory = Unsafe.IsNullRef(in iid) + ? GetActivationFactory(runtimeClassName) + : GetActivationFactory(runtimeClassName, in iid); + + Volatile.Write(ref location, activationFactory); + + return activationFactory; + } } \ No newline at end of file