Skip to content

Theraot.Collections.ThreadSafe.WeakDelegateCollection

Alfonso J. Ramos edited this page Nov 10, 2015 · 3 revisions

WeakDelegateCollection

This class does all the heavy work behind WeakEvent<TEventArgs>. So all the benefits listed for it - except the easy to use interface - are true for it... noting that WeakDelegateCollection is not generic.

  • Controlling reentry: if the execution of the event handler causes the event to fire again, it will not stack them, nor starve other handlers. Instead the second firing of the event is automatically scheduled to run after the current one finishes. This is done thanks to ReentryGuard.
  • Taking care of separating the reference to the object from the reference to the delegate. Internally the delegate is reconstructed and a GCHandle is used to keep a weak reference to the new instance. The original delegate instance is discarded. This is done thanks to WeakDelegateNeedle.
  • Comparison of delegates is done by its target object and the associated MethodInfo, so you don't need the original delegate to unsubscribe from the event. Meaning that you don't have to keep an strong reference yourself.
  • All references that have dead delegates will be cleaned. This is done by WeakCollection by using the garbage collection notification mechanism provided by GCMonitor - which in turn is a weak event. This is a cyclic dependency.