ObserveOn.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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.Concurrency;
  5. using System.Threading;
  6. namespace System.Reactive.Linq.Observαble
  7. {
  8. class ObserveOn<TSource> : Producer<TSource>
  9. {
  10. private readonly IObservable<TSource> _source;
  11. private readonly IScheduler _scheduler;
  12. public ObserveOn(IObservable<TSource> source, IScheduler scheduler)
  13. {
  14. _source = source;
  15. _scheduler = scheduler;
  16. }
  17. #if !NO_SYNCCTX
  18. private readonly SynchronizationContext _context;
  19. public ObserveOn(IObservable<TSource> source, SynchronizationContext context)
  20. {
  21. _source = source;
  22. _context = context;
  23. }
  24. #endif
  25. protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
  26. {
  27. #if !NO_SYNCCTX
  28. if (_context != null)
  29. {
  30. var sink = new ς(this, observer, cancel);
  31. setSink(sink);
  32. return _source.Subscribe(sink);
  33. }
  34. else
  35. #endif
  36. {
  37. var sink = new ObserveOnObserver<TSource>(_scheduler, observer, cancel);
  38. setSink(sink);
  39. return _source.Subscribe(sink);
  40. }
  41. }
  42. #if !NO_SYNCCTX
  43. class ς : Sink<TSource>, IObserver<TSource>
  44. {
  45. private readonly ObserveOn<TSource> _parent;
  46. public ς(ObserveOn<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
  47. : base(observer, cancel)
  48. {
  49. _parent = parent;
  50. }
  51. public void OnNext(TSource value)
  52. {
  53. _parent._context.PostWithStartComplete(() =>
  54. {
  55. base._observer.OnNext(value);
  56. });
  57. }
  58. public void OnError(Exception error)
  59. {
  60. _parent._context.PostWithStartComplete(() =>
  61. {
  62. base._observer.OnError(error);
  63. base.Dispose();
  64. });
  65. }
  66. public void OnCompleted()
  67. {
  68. _parent._context.PostWithStartComplete(() =>
  69. {
  70. base._observer.OnCompleted();
  71. base.Dispose();
  72. });
  73. }
  74. }
  75. #endif
  76. }
  77. }
  78. #endif