Skip to content

Instantly share code, notes, and snippets.

@augustoproiete
Forked from ayende/PhantomReferenceQueue.cs
Created January 9, 2019 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save augustoproiete/2173303200aec8978f04a7c55e82d04d to your computer and use it in GitHub Desktop.
Save augustoproiete/2173303200aec8978f04a7c55e82d04d to your computer and use it in GitHub Desktop.
public class PhatomReferenceQueue<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 PhatomReference(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 PhatomReference
{
THandle _handle;
PhatomReferenceQueue<THandle> _parent;
public PhatomReference(PhatomReferenceQueue<THandle> phatomReferenceQueue, THandle handle)
{
_parent = phatomReferenceQueue;
_handle = handle;
}
~PhatomReference()
{
_parent._queue.Add(_handle);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment