Synchronization.Synchronize.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.Concurrency
  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. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "2", Justification = "Visibility restricted to friend assemblies. Those should be correct by inspection.")]
  22. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  23. {
  24. var sink = new _(this, observer, cancel);
  25. setSink(sink);
  26. return _source.SubscribeSafe(sink);
  27. }
  28. class _ : Sink<TSource>, IObserver<TSource>
  29. {
  30. private readonly Synchronize<TSource> _parent;
  31. private readonly object _gate;
  32. public _(Synchronize<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  33. : base(observer, cancel)
  34. {
  35. _parent = parent;
  36. _gate = _parent._gate ?? new object();
  37. }
  38. public void OnNext(TSource value)
  39. {
  40. lock (_gate)
  41. {
  42. base._observer.OnNext(value);
  43. }
  44. }
  45. public void OnError(Exception error)
  46. {
  47. lock (_gate)
  48. {
  49. base._observer.OnError(error);
  50. base.Dispose();
  51. }
  52. }
  53. public void OnCompleted()
  54. {
  55. lock (_gate)
  56. {
  57. base._observer.OnCompleted();
  58. base.Dispose();
  59. }
  60. }
  61. }
  62. }
  63. }
  64. #endif