Last active
January 10, 2019 14:40
-
-
Save ayende/f3989f240111d95ba6aac61b9b6858b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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