Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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