Synchronize.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #if !NO_PERF
  5. using System;
  6. namespace System.Reactive.Linq.ObservableImpl
  7. {
  8. class Synchronize<TSource> : Producer<TSource>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly object _gate;
  12. public Synchronize(IObservable<TSource> source, object gate)
  13. {
  14. _source = source;
  15. _gate = gate;
  16. }
  17. public Synchronize(IObservable<TSource> source)
  18. {
  19. _source = source;
  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 _source.Subscribe(sink);
  26. }
  27. class _ : Sink<TSource>, IObserver<TSource>
  28. {
  29. private readonly Synchronize<TSource> _parent;
  30. private object _gate;
  31. public _(Synchronize<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  32. : base(observer, cancel)
  33. {
  34. _parent = parent;
  35. _gate = _parent._gate ?? new object();
  36. }
  37. public void OnNext(TSource value)
  38. {
  39. lock (_gate)
  40. {
  41. base._observer.OnNext(value);
  42. }
  43. }
  44. public void OnError(Exception error)
  45. {
  46. lock (_gate)
  47. {
  48. base._observer.OnError(error);
  49. base.Dispose();
  50. }
  51. }
  52. public void OnCompleted()
  53. {
  54. lock (_gate)
  55. {
  56. base._observer.OnCompleted();
  57. base.Dispose();
  58. }
  59. }
  60. }
  61. }
  62. }
  63. #endif