EventPatternSourceBase.cs 5.4 KB

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