Range.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.Reactive.Disposables;
  6. namespace System.Reactive.Linq.Observαble
  7. {
  8. class Range : Producer<int>
  9. {
  10. private readonly int _start;
  11. private readonly int _count;
  12. private readonly IScheduler _scheduler;
  13. public Range(int start, int count, IScheduler scheduler)
  14. {
  15. _start = start;
  16. _count = count;
  17. _scheduler = scheduler;
  18. }
  19. protected override IDisposable Run(IObserver<int> observer, IDisposable cancel, Action<IDisposable> setSink)
  20. {
  21. var sink = new _(this, observer, cancel);
  22. setSink(sink);
  23. return sink.Run();
  24. }
  25. class _ : Sink<int>
  26. {
  27. private readonly Range _parent;
  28. public _(Range parent, IObserver<int> observer, IDisposable cancel)
  29. : base(observer, cancel)
  30. {
  31. _parent = parent;
  32. }
  33. public IDisposable Run()
  34. {
  35. var longRunning = _parent._scheduler.AsLongRunning();
  36. if (longRunning != null)
  37. {
  38. return longRunning.ScheduleLongRunning(0, Loop);
  39. }
  40. else
  41. {
  42. return _parent._scheduler.Schedule(0, LoopRec);
  43. }
  44. }
  45. private void Loop(int i, ICancelable cancel)
  46. {
  47. while (!cancel.IsDisposed && i < _parent._count)
  48. {
  49. base._observer.OnNext(_parent._start + i);
  50. i++;
  51. }
  52. if (!cancel.IsDisposed)
  53. base._observer.OnCompleted();
  54. base.Dispose();
  55. }
  56. private void LoopRec(int i, Action<int> recurse)
  57. {
  58. if (i < _parent._count)
  59. {
  60. base._observer.OnNext(_parent._start + i);
  61. recurse(i + 1);
  62. }
  63. else
  64. {
  65. base._observer.OnCompleted();
  66. base.Dispose();
  67. }
  68. }
  69. }
  70. }
  71. }
  72. #endif