Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace System
- {
- /// <summary>
- /// Encapsulates an event publisher and a handler while still allowing the objects to be garbage collected.
- /// </summary>
- /// <typeparam name="TTarget">The type of the class that declares the handler.</typeparam>
- /// <typeparam name="TEventArgs">The type of <see cref="EventArgs"/> this event handler accepts as an argument.</typeparam>
- public class WeakHandler<TTarget, TEventArgs>
- where TTarget : class, IWeakHandler<TEventArgs>
- where TEventArgs : EventArgs
- {
- private WeakReference _target;
- /// <summary>
- /// Initializes a new object of <see cref="WeakHandler"/>.
- /// </summary>
- /// <param name="target">The object that handles the event.</param>
- public WeakHandler(TTarget target)
- {
- if (target == null) throw new ArgumentNullException("target");
- _target = new WeakReference(target);
- }
- /// <summary>
- /// The method that should actually be subscribed to the event.
- /// </summary>
- /// <param name="sender">The object that publishes the event.</param>
- /// <param name="e">The <see cref="EventArgs"/> to be passed to the event handler.</param>
- public virtual void OnEventRaised(object sender, TEventArgs e)
- {
- if (Target != null)
- Target.OnEventRaised(sender, e);
- }
- /// <summary>
- /// The object that handles the event.
- /// </summary>
- public TTarget Target
- {
- get
- {
- return (TTarget)_target.Target;
- }
- }
- }
- /// <summary>
- /// Defines an event handler of the specified <see cref="EventArgs"/>.
- /// </summary>
- /// <typeparam name="TEventArgs">The <see cref="EventArgs"/> type of this event.</typeparam>
- public interface IWeakHandler<TEventArgs>
- where TEventArgs : EventArgs
- {
- /// <summary>
- /// The method to be raised when the event is fired.
- /// </summary>
- /// <param name="sender">The object that raised the event.</param>
- /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
- void OnEventRaised(object sender, TEventArgs e);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement