EventPatternSourceBaseInternal.cs 5.8 KB

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