Synchronization.Synchronize.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #nullable disable
  5. namespace System.Reactive.Concurrency
  6. {
  7. internal sealed class Synchronize<TSource> : Producer<TSource, Synchronize<TSource>._>
  8. {
  9. private readonly IObservable<TSource> _source;
  10. private readonly object _gate;
  11. public Synchronize(IObservable<TSource> source, object gate)
  12. {
  13. _source = source;
  14. _gate = gate;
  15. }
  16. public Synchronize(IObservable<TSource> source)
  17. {
  18. _source = source;
  19. }
  20. protected override _ CreateSink(IObserver<TSource> observer) => new _(this, observer);
  21. [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 void Run(_ sink) => sink.Run(_source);
  23. internal sealed class _ : IdentitySink<TSource>
  24. {
  25. private readonly object _gate;
  26. public _(Synchronize<TSource> parent, IObserver<TSource> observer)
  27. : base(observer)
  28. {
  29. _gate = parent._gate ?? new object();
  30. }
  31. public override void OnNext(TSource value)
  32. {
  33. lock (_gate)
  34. {
  35. ForwardOnNext(value);
  36. }
  37. }
  38. public override void OnError(Exception error)
  39. {
  40. lock (_gate)
  41. {
  42. ForwardOnError(error);
  43. }
  44. }
  45. public override void OnCompleted()
  46. {
  47. lock (_gate)
  48. {
  49. ForwardOnCompleted();
  50. }
  51. }
  52. }
  53. }
  54. }