diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/TrackerObjectManager.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/TrackerObjectManager.NativeAot.cs index 46d58c3d553974..7bc461cef8d54c 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/TrackerObjectManager.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/TrackerObjectManager.NativeAot.cs @@ -196,6 +196,7 @@ internal static void DetachNonPromotedObjects() } // Callback implementation of IFindReferenceTargetsCallback + [EagerStaticClassConstruction] internal static unsafe class FindReferenceTargetsCallback { // Define an on-stack compatible COM instance to avoid allocating diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs index ec40677dc62384..fb2210d780173f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs @@ -444,12 +444,18 @@ private IntPtr AsUserDefined(in Guid riid) private void SetFlag(CreateComInterfaceFlagsEx flag) { - Interlocked.Or(ref Flags, flag); + // Interlocked.Orcannot be used here. It would trigger type checks that can cause + // deadlocks when called during a GC by NativeAOT TrackerObjectManager. + int setMask = (int)flag; + Interlocked.Or(ref Unsafe.As(ref Flags), setMask); } private void ResetFlag(CreateComInterfaceFlagsEx flag) { - Interlocked.And(ref Flags, ~flag); + // Interlocked.Andcannot be used here. It would trigger type checks that can cause + // deadlocks when called during a GC by NativeAOT TrackerObjectManager. + int resetMask = ~(int)flag; + Interlocked.And(ref Unsafe.As(ref Flags), resetMask); } private static uint GetTrackerCount(ulong c)