Sink.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System.Threading;
  4. namespace System.Reactive
  5. {
  6. /// <summary>
  7. /// Base class for implementation of query operators, providing a lightweight sink that can be disposed to mute the outgoing observer.
  8. /// </summary>
  9. /// <typeparam name="TSource">Type of the resulting sequence's elements.</typeparam>
  10. /// <remarks>Implementations of sinks are responsible to enforce the message grammar on the associated observer. Upon sending a terminal message, a pairing Dispose call should be made to trigger cancellation of related resources and to mute the outgoing observer.</remarks>
  11. internal abstract class Sink<TSource> : IDisposable
  12. {
  13. protected internal volatile IObserver<TSource> _observer;
  14. private IDisposable _cancel;
  15. public Sink(IObserver<TSource> observer, IDisposable cancel)
  16. {
  17. _observer = observer;
  18. _cancel = cancel;
  19. }
  20. public virtual void Dispose()
  21. {
  22. _observer = NopObserver<TSource>.Instance;
  23. var cancel = Interlocked.Exchange(ref _cancel, null);
  24. if (cancel != null)
  25. {
  26. cancel.Dispose();
  27. }
  28. }
  29. public IObserver<TSource> GetForwarder()
  30. {
  31. return new _(this);
  32. }
  33. class _ : IObserver<TSource>
  34. {
  35. private readonly Sink<TSource> _forward;
  36. public _(Sink<TSource> forward)
  37. {
  38. _forward = forward;
  39. }
  40. public void OnNext(TSource value)
  41. {
  42. _forward._observer.OnNext(value);
  43. }
  44. public void OnError(Exception error)
  45. {
  46. _forward._observer.OnError(error);
  47. _forward.Dispose();
  48. }
  49. public void OnCompleted()
  50. {
  51. _forward._observer.OnCompleted();
  52. _forward.Dispose();
  53. }
  54. }
  55. }
  56. }
  57. #endif