-
-
Save augustoproiete/2173303200aec8978f04a7c55e82d04d 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 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