Advertisement
Shimmy

WeakHandler

Feb 1st, 2012
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. namespace System
  2. {
  3.  
  4. /// <summary>
  5. /// Encapsulates an event publisher and a handler while still allowing the objects to be garbage collected.
  6. /// </summary>
  7. /// <typeparam name="TTarget">The type of the class that declares the handler.</typeparam>
  8. /// <typeparam name="TEventArgs">The type of <see cref="EventArgs"/> this event handler accepts as an argument.</typeparam>
  9. public class WeakHandler<TTarget, TEventArgs>
  10. where TTarget : class, IWeakHandler<TEventArgs>
  11. where TEventArgs : EventArgs
  12. {
  13.  
  14. private WeakReference _target;
  15.  
  16. /// <summary>
  17. /// Initializes a new object of <see cref="WeakHandler"/>.
  18. /// </summary>
  19. /// <param name="target">The object that handles the event.</param>
  20. public WeakHandler(TTarget target)
  21. {
  22. if (target == null) throw new ArgumentNullException("target");
  23.  
  24. _target = new WeakReference(target);
  25. }
  26.  
  27. /// <summary>
  28. /// The method that should actually be subscribed to the event.
  29. /// </summary>
  30. /// <param name="sender">The object that publishes the event.</param>
  31. /// <param name="e">The <see cref="EventArgs"/> to be passed to the event handler.</param>
  32. public virtual void OnEventRaised(object sender, TEventArgs e)
  33. {
  34. if (Target != null)
  35. Target.OnEventRaised(sender, e);
  36. }
  37.  
  38. /// <summary>
  39. /// The object that handles the event.
  40. /// </summary>
  41. public TTarget Target
  42. {
  43. get
  44. {
  45. return (TTarget)_target.Target;
  46. }
  47. }
  48. }
  49.  
  50. /// <summary>
  51. /// Defines an event handler of the specified <see cref="EventArgs"/>.
  52. /// </summary>
  53. /// <typeparam name="TEventArgs">The <see cref="EventArgs"/> type of this event.</typeparam>
  54. public interface IWeakHandler<TEventArgs>
  55. where TEventArgs : EventArgs
  56. {
  57. /// <summary>
  58. /// The method to be raised when the event is fired.
  59. /// </summary>
  60. /// <param name="sender">The object that raised the event.</param>
  61. /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
  62. void OnEventRaised(object sender, TEventArgs e);
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement