ForEach.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. #if !NO_PERF
  5. using System;
  6. using System.Threading;
  7. namespace System.Reactive.Linq.ObservableImpl
  8. {
  9. class ForEach<TSource>
  10. {
  11. public class _ : IObserver<TSource>
  12. {
  13. private readonly Action<TSource> _onNext;
  14. private readonly Action _done;
  15. private Exception _exception;
  16. private int _stopped;
  17. public _(Action<TSource> onNext, Action done)
  18. {
  19. _onNext = onNext;
  20. _done = done;
  21. _stopped = 0;
  22. }
  23. public Exception Error
  24. {
  25. get { return _exception; }
  26. }
  27. public void OnNext(TSource value)
  28. {
  29. if (_stopped == 0)
  30. {
  31. try
  32. {
  33. _onNext(value);
  34. }
  35. catch (Exception ex)
  36. {
  37. OnError(ex);
  38. }
  39. }
  40. }
  41. public void OnError(Exception error)
  42. {
  43. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  44. {
  45. _exception = error;
  46. _done();
  47. }
  48. }
  49. public void OnCompleted()
  50. {
  51. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  52. {
  53. _done();
  54. }
  55. }
  56. }
  57. public class ForEachImpl : IObserver<TSource>
  58. {
  59. private readonly Action<TSource, int> _onNext;
  60. private readonly Action _done;
  61. private int _index;
  62. private Exception _exception;
  63. private int _stopped;
  64. public ForEachImpl(Action<TSource, int> onNext, Action done)
  65. {
  66. _onNext = onNext;
  67. _done = done;
  68. _index = 0;
  69. _stopped = 0;
  70. }
  71. public Exception Error
  72. {
  73. get { return _exception; }
  74. }
  75. public void OnNext(TSource value)
  76. {
  77. if (_stopped == 0)
  78. {
  79. try
  80. {
  81. _onNext(value, checked(_index++));
  82. }
  83. catch (Exception ex)
  84. {
  85. OnError(ex);
  86. }
  87. }
  88. }
  89. public void OnError(Exception error)
  90. {
  91. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  92. {
  93. _exception = error;
  94. _done();
  95. }
  96. }
  97. public void OnCompleted()
  98. {
  99. if (Interlocked.Exchange(ref _stopped, 1) == 0)
  100. {
  101. _done();
  102. }
  103. }
  104. }
  105. }
  106. }
  107. #endif