RefCount.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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;
  4. using System.Reactive.Disposables;
  5. using System.Reactive.Subjects;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. class RefCount<TSource> : Producer<TSource>
  9. {
  10. private readonly IConnectableObservable<TSource> _source;
  11. private readonly object _gate;
  12. private int _count;
  13. private IDisposable _connectableSubscription;
  14. public RefCount(IConnectableObservable<TSource> source)
  15. {
  16. _source = source;
  17. _gate = new object();
  18. _count = 0;
  19. _connectableSubscription = default(IDisposable);
  20. }
  21. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  22. {
  23. var sink = new _(this, observer, cancel);
  24. setSink(sink);
  25. return sink.Run();
  26. }
  27. class _ : Sink<TSource>, IObserver<TSource>
  28. {
  29. private readonly RefCount<TSource> _parent;
  30. public _(RefCount<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  31. : base(observer, cancel)
  32. {
  33. _parent = parent;
  34. }
  35. public IDisposable Run()
  36. {
  37. var subscription = _parent._source.SubscribeSafe(this);
  38. lock (_parent._gate)
  39. {
  40. if (++_parent._count == 1)
  41. {
  42. _parent._connectableSubscription = _parent._source.Connect();
  43. }
  44. }
  45. return Disposable.Create(() =>
  46. {
  47. subscription.Dispose();
  48. lock (_parent._gate)
  49. {
  50. if (--_parent._count == 0)
  51. {
  52. _parent._connectableSubscription.Dispose();
  53. }
  54. }
  55. });
  56. }
  57. public void OnNext(TSource value)
  58. {
  59. base._observer.OnNext(value);
  60. }
  61. public void OnError(Exception error)
  62. {
  63. base._observer.OnError(error);
  64. base.Dispose();
  65. }
  66. public void OnCompleted()
  67. {
  68. base._observer.OnCompleted();
  69. base.Dispose();
  70. }
  71. }
  72. }
  73. }
  74. #endif