namespace System { /// /// Encapsulates an event publisher and a handler while still allowing the objects to be garbage collected. /// /// The type of the class that declares the handler. /// The type of this event handler accepts as an argument. public class WeakHandler where TTarget : class, IWeakHandler where TEventArgs : EventArgs { private WeakReference _target; /// /// Initializes a new object of . /// /// The object that handles the event. public WeakHandler(TTarget target) { if (target == null) throw new ArgumentNullException("target"); _target = new WeakReference(target); } /// /// The method that should actually be subscribed to the event. /// /// The object that publishes the event. /// The to be passed to the event handler. public virtual void OnEventRaised(object sender, TEventArgs e) { if (Target != null) Target.OnEventRaised(sender, e); } /// /// The object that handles the event. /// public TTarget Target { get { return (TTarget)_target.Target; } } } /// /// Defines an event handler of the specified . /// /// The type of this event. public interface IWeakHandler where TEventArgs : EventArgs { /// /// The method to be raised when the event is fired. /// /// The object that raised the event. /// The of the event. void OnEventRaised(object sender, TEventArgs e); } }