Skip to content

Instantly share code, notes, and snippets.

@ayende
Last active January 10, 2019 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ayende/f3989f240111d95ba6aac61b9b6858b2 to your computer and use it in GitHub Desktop.
Save ayende/f3989f240111d95ba6aac61b9b6858b2 to your computer and use it in GitHub Desktop.
public class PhantomReferenceQueue<THandle>
{
private BlockingCollection<THandle> _queue = new BlockingCollection<THandle>();
private ConditionalWeakTable<object, PhatomReference> _refs = new ConditionalWeakTable<object, PhatomReference>();
public void Register(object instance, THandle handle)
{
_refs.Add(instance, new PhantomReference(this, handle));
}
public void Unregister(object instance)
{
if (_refs.TryGetValue(instance, out var val))
GC.SuppressFinalize(val);
_refs.Remove(instance);
}
public THandle Poll()
{
return _queue.Take();
}
private class PhantomReference
{
THandle _handle;
PhantomReferenceQueue<THandle> _parent;
public PhantomReference(PhantomReferenceQueue<THandle> parent, THandle handle)
{
_parent = parent;
_handle = handle;
}
~PhantomReference()
{
_parent._queue.Add(_handle);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment