From 10a995276e09559ea4347a4e0c88f4402400132b Mon Sep 17 00:00:00 2001 From: Aaron Robinson Date: Fri, 3 Oct 2025 10:57:36 -0700 Subject: [PATCH] Revert "Use a ReaderWriterLockSlim in RcwCache (#117792)" This reverts commit a0748134c931391cf310f8eb4b78d4874f378463. --- .../Runtime/InteropServices/ComWrappers.cs | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) 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 2945a99d9b8c44..840f05dc00f856 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 @@ -1289,7 +1289,7 @@ private static void AddWrapperToReferenceTrackerHandleCache(NativeObjectWrapper private sealed class RcwCache { - private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); + private readonly Lock _lock = new Lock(useTrivialWaits: true); private readonly Dictionary _cache = []; /// @@ -1301,8 +1301,7 @@ private sealed class RcwCache /// The proxy object currently in the cache for or the proxy object owned by if no entry exists and the corresponding native wrapper. public (NativeObjectWrapper actualWrapper, object actualProxy) GetOrAddProxyForComInstance(IntPtr comPointer, NativeObjectWrapper wrapper, object comProxy) { - _lock.EnterWriteLock(); - try + lock (_lock) { Debug.Assert(wrapper.ProxyHandle.Target == comProxy); ref GCHandle rcwEntry = ref CollectionsMarshal.GetValueRefOrAddDefault(_cache, comPointer, out bool exists); @@ -1337,16 +1336,11 @@ private sealed class RcwCache // Return our target object. return (wrapper, comProxy); } - finally - { - _lock.ExitWriteLock(); - } } public object? FindProxyForComInstance(IntPtr comPointer) { - _lock.EnterReadLock(); - try + lock (_lock) { if (_cache.TryGetValue(comPointer, out GCHandle existingHandle)) { @@ -1363,16 +1357,11 @@ private sealed class RcwCache return null; } - finally - { - _lock.ExitReadLock(); - } } public void Remove(IntPtr comPointer, NativeObjectWrapper wrapper) { - _lock.EnterWriteLock(); - try + lock (_lock) { // TryGetOrCreateObjectForComInstanceInternal may have put a new entry into the cache // in the time between the GC cleared the contents of the GC handle but before the @@ -1387,10 +1376,6 @@ public void Remove(IntPtr comPointer, NativeObjectWrapper wrapper) cachedRef.Free(); } } - finally - { - _lock.ExitWriteLock(); - } } }