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 Lock _lock = new Lock(useTrivialWaits: true);
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private readonly Dictionary<IntPtr, GCHandle> _cache = [];

/// <summary>
Expand All @@ -1301,7 +1301,8 @@ 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 (_lock)
_lock.EnterWriteLock();
try
{
Debug.Assert(wrapper.ProxyHandle.Target == comProxy);
ref GCHandle rcwEntry = ref CollectionsMarshal.GetValueRefOrAddDefault(_cache, comPointer, out bool exists);
Expand Down Expand Up @@ -1336,11 +1337,16 @@ private sealed class RcwCache
// Return our target object.
return (wrapper, comProxy);
}
finally
{
_lock.ExitWriteLock();
}
}

public object? FindProxyForComInstance(IntPtr comPointer)
{
lock (_lock)
_lock.EnterReadLock();
try
{
if (_cache.TryGetValue(comPointer, out GCHandle existingHandle))
{
Expand All @@ -1357,11 +1363,16 @@ private sealed class RcwCache

return null;
}
finally
{
_lock.ExitReadLock();
}
}

public void Remove(IntPtr comPointer, NativeObjectWrapper wrapper)
{
lock (_lock)
_lock.EnterWriteLock();
try
{
// 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 @@ -1376,6 +1387,10 @@ public void Remove(IntPtr comPointer, NativeObjectWrapper wrapper)
cachedRef.Free();
}
}
finally
{
_lock.ExitWriteLock();
}
}
}

Expand Down
Loading