Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<IntPtr, GCHandle> _cache = [];

/// <summary>
Expand All @@ -1301,8 +1301,7 @@ private sealed class RcwCache
/// <returns>The proxy object currently in the cache for <paramref name="comPointer"/> or the proxy object owned by <paramref name="wrapper"/> if no entry exists and the corresponding native wrapper.</returns>
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);
Expand Down Expand Up @@ -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)
Copy link
Contributor

@rhuijben rhuijben Oct 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here a readlock is not enough. It updates the hashtable under some circumstances, which may go concurrent under a read lock.

Copy link
Contributor

@rhuijben rhuijben Oct 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Upgrading to a write lock before the update (_cache.Remove()) may help too... But the single lock is probably just as easy.

{
if (_cache.TryGetValue(comPointer, out GCHandle existingHandle))
{
Expand All @@ -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
Expand All @@ -1387,10 +1376,6 @@ public void Remove(IntPtr comPointer, NativeObjectWrapper wrapper)
cachedRef.Free();
}
}
finally
{
_lock.ExitWriteLock();
}
}
}

Expand Down
Loading