ForEach.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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.Threading;
  5. namespace System.Reactive.Linq.ObservableImpl
  6. {
  7. class ForEach<TSource>
  8. {
  9. public class _ : IObserver<TSource>
  10. {
  11. private readonly Action<TSource> _onNext;
  12. private readonly Action _done;
  13. private Exception _exception;
  14. private int _stopped;
  15. public _(Action<TSource> onNext, Action done)
  16. {
  17. _onNext = onNext;
  18. _done = done;
  19. _stopped = 0;
  20. }
  21. public Exception Error
  22. {
  23. get { return _exception; }
  24. }
  25. public void OnNext(TSource value)
  26. {
  27. if (_stopped == 0)
  28. {
  29. try
  30. {
  31. _onNext(value);
  32. }
  33. catch (Exception ex)
  34. {
  35. OnError(ex);
  36. }
  37. }
  38. }
  39. public void OnError(Exception error)
  40. {
  41. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  42. {
  43. _exception = error;
  44. _done();
  45. }
  46. }
  47. public void OnCompleted()
  48. {
  49. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  50. {
  51. _done();
  52. }
  53. }
  54. }
  55. public class ForEachImpl : IObserver<TSource>
  56. {
  57. private readonly Action<TSource, int> _onNext;
  58. private readonly Action _done;
  59. private int _index;
  60. private Exception _exception;
  61. private int _stopped;
  62. public ForEachImpl(Action<TSource, int> onNext, Action done)
  63. {
  64. _onNext = onNext;
  65. _done = done;
  66. _index = 0;
  67. _stopped = 0;
  68. }
  69. public Exception Error
  70. {
  71. get { return _exception; }
  72. }
  73. public void OnNext(TSource value)
  74. {
  75. if (_stopped == 0)
  76. {
  77. try
  78. {
  79. _onNext(value, checked(_index++));
  80. }
  81. catch (Exception ex)
  82. {
  83. OnError(ex);
  84. }
  85. }
  86. }
  87. public void OnError(Exception error)
  88. {
  89. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  90. {
  91. _exception = error;
  92. _done();
  93. }
  94. }
  95. public void OnCompleted()
  96. {
  97. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  98. {
  99. _done();
  100. }
  101. }
  102. }
  103. }
  104. }
  105. #endif