Synchronization.Synchronize.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. namespace System.Reactive.Concurrency
  5. {
  6. class Synchronize<TSource> : Producer<TSource>
  7. {
  8. private readonly IObservable<TSource> _source;
  9. private readonly object _gate;
  10. public Synchronize(IObservable<TSource> source, object gate)
  11. {
  12. _source = source;
  13. _gate = gate;
  14. }
  15. public Synchronize(IObservable<TSource> source)
  16. {
  17. _source = source;
  18. }
  19. [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.")]
  20. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  21. {
  22. var sink = new _(this, observer, cancel);
  23. setSink(sink);
  24. return _source.SubscribeSafe(sink);
  25. }
  26. class _ : Sink<TSource>, IObserver<TSource>
  27. {
  28. private readonly Synchronize<TSource> _parent;
  29. private readonly object _gate;
  30. public _(Synchronize<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  31. : base(observer, cancel)
  32. {
  33. _parent = parent;
  34. _gate = _parent._gate ?? new object();
  35. }
  36. public void OnNext(TSource value)
  37. {
  38. lock (_gate)
  39. {
  40. base._observer.OnNext(value);
  41. }
  42. }
  43. public void OnError(Exception error)
  44. {
  45. lock (_gate)
  46. {
  47. base._observer.OnError(error);
  48. base.Dispose();
  49. }
  50. }
  51. public void OnCompleted()
  52. {
  53. lock (_gate)
  54. {
  55. base._observer.OnCompleted();
  56. base.Dispose();
  57. }
  58. }
  59. }
  60. }
  61. }
  62. #endif