EventPatternSourceBase.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.Collections.Generic;
  3. namespace System.Reactive
  4. {
  5. /// <summary>
  6. /// Base class for classes that expose an observable sequence as a well-known event pattern (sender, event arguments).
  7. /// Contains functionality to maintain a map of event handler delegates to observable sequence subscriptions. Subclasses
  8. /// should only add an event with custom add and remove methods calling into the base class's operations.
  9. /// </summary>
  10. /// <typeparam name="TSender">The type of the sender that raises the event.</typeparam>
  11. /// <typeparam name="TEventArgs">The type of the event data generated by the event.</typeparam>
  12. public abstract class EventPatternSourceBase<TSender, TEventArgs>
  13. #if !NO_EVENTARGS_CONSTRAINT
  14. where TEventArgs : EventArgs
  15. #endif
  16. {
  17. private readonly IObservable<EventPattern<TSender, TEventArgs>> _source;
  18. private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions;
  19. private readonly Action<Action<TSender, TEventArgs>, /*object,*/ EventPattern<TSender, TEventArgs>> _invokeHandler;
  20. /// <summary>
  21. /// Creates a new event pattern source.
  22. /// </summary>
  23. /// <param name="source">Source sequence to expose as an event.</param>
  24. /// <param name="invokeHandler">Delegate used to invoke the event for each element of the sequence.</param>
  25. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="invokeHandler"/> is null.</exception>
  26. protected EventPatternSourceBase(IObservable<EventPattern<TSender, TEventArgs>> source, Action<Action<TSender, TEventArgs>, /*object,*/ EventPattern<TSender, TEventArgs>> invokeHandler)
  27. {
  28. if (source == null)
  29. throw new ArgumentNullException("source");
  30. if (invokeHandler == null)
  31. throw new ArgumentNullException("invokeHandler");
  32. _source = source;
  33. _invokeHandler = invokeHandler;
  34. _subscriptions = new Dictionary<Delegate, Stack<IDisposable>>();
  35. }
  36. /// <summary>
  37. /// Adds the specified event handler, causing a subscription to the underlying source.
  38. /// </summary>
  39. /// <param name="handler">Event handler to add. The same delegate should be passed to the Remove operation in order to remove the event handler.</param>
  40. /// <param name="invoke">Invocation delegate to raise the event in the derived class.</param>
  41. /// <exception cref="ArgumentNullException"><paramref name="handler"/> or <paramref name="invoke"/> is null.</exception>
  42. protected void Add(Delegate handler, Action<TSender, TEventArgs> invoke)
  43. {
  44. if (handler == null)
  45. throw new ArgumentNullException("handler");
  46. if (invoke == null)
  47. throw new ArgumentNullException("invoke");
  48. var gate = new object();
  49. var isAdded = false;
  50. var isDone = false;
  51. var remove = new Action(() =>
  52. {
  53. lock (gate)
  54. {
  55. if (isAdded)
  56. Remove(handler);
  57. else
  58. isDone = true;
  59. }
  60. });
  61. //
  62. // [OK] Use of unsafe Subscribe: non-pretentious wrapper of an observable in an event; exceptions can occur during +=.
  63. //
  64. var d = _source.Subscribe/*Unsafe*/(
  65. x => _invokeHandler(invoke, /*this,*/ x),
  66. ex => { remove(); ex.Throw(); },
  67. () => remove()
  68. );
  69. lock (gate)
  70. {
  71. if (!isDone)
  72. {
  73. Add(handler, d);
  74. isAdded = true;
  75. }
  76. }
  77. }
  78. private void Add(Delegate handler, IDisposable disposable)
  79. {
  80. lock (_subscriptions)
  81. {
  82. var l = new Stack<IDisposable>();
  83. if (!_subscriptions.TryGetValue(handler, out l))
  84. _subscriptions[handler] = l = new Stack<IDisposable>();
  85. l.Push(disposable);
  86. }
  87. }
  88. /// <summary>
  89. /// Removes the specified event handler, causing a disposal of the corresponding subscription to the underlying source that was created during the Add operation.
  90. /// </summary>
  91. /// <param name="handler">Event handler to remove. This should be the same delegate as one that was passed to the Add operation.</param>
  92. /// <exception cref="ArgumentNullException"><paramref name="handler"/> is null.</exception>
  93. protected void Remove(Delegate handler)
  94. {
  95. if (handler == null)
  96. throw new ArgumentNullException("handler");
  97. var d = default(IDisposable);
  98. lock (_subscriptions)
  99. {
  100. var l = new Stack<IDisposable>();
  101. if (_subscriptions.TryGetValue(handler, out l))
  102. {
  103. d = l.Pop();
  104. if (l.Count == 0)
  105. _subscriptions.Remove(handler);
  106. }
  107. }
  108. if (d != null)
  109. d.Dispose();
  110. }
  111. }
  112. }