1
0

Synchronize.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Threading;
  5. using System.Threading;
  6. namespace System.Reactive.Linq
  7. {
  8. public partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<TSource> Synchronize<TSource>(this IAsyncObservable<TSource> source)
  11. {
  12. if (source == null)
  13. throw new ArgumentNullException(nameof(source));
  14. return Create(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.Synchronize(observer)));
  15. }
  16. public static IAsyncObservable<TSource> Synchronize<TSource>(this IAsyncObservable<TSource> source, IAsyncGate gate)
  17. {
  18. if (source == null)
  19. throw new ArgumentNullException(nameof(source));
  20. if (gate == null)
  21. throw new ArgumentNullException(nameof(gate));
  22. return CreateAsyncObservable<TSource>.From(
  23. source,
  24. gate,
  25. static (source, gate, observer) => source.SubscribeSafeAsync(AsyncObserver.Synchronize(observer, gate)));
  26. }
  27. }
  28. public partial class AsyncObserver
  29. {
  30. public static IAsyncObserver<TSource> Synchronize<TSource>(IAsyncObserver<TSource> observer)
  31. {
  32. if (observer == null)
  33. throw new ArgumentNullException(nameof(observer));
  34. return Synchronize(observer, new AsyncGate());
  35. }
  36. public static IAsyncObserver<TSource> Synchronize<TSource>(IAsyncObserver<TSource> observer, IAsyncGate gate)
  37. {
  38. if (observer == null)
  39. throw new ArgumentNullException(nameof(observer));
  40. if (gate == null)
  41. throw new ArgumentNullException(nameof(gate));
  42. return Create<TSource>(
  43. async x =>
  44. {
  45. using (await gate.LockAsync().ConfigureAwait(false))
  46. {
  47. await observer.OnNextAsync(x).ConfigureAwait(false);
  48. }
  49. },
  50. async ex =>
  51. {
  52. using (await gate.LockAsync().ConfigureAwait(false))
  53. {
  54. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  55. }
  56. },
  57. async () =>
  58. {
  59. using (await gate.LockAsync().ConfigureAwait(false))
  60. {
  61. await observer.OnCompletedAsync().ConfigureAwait(false);
  62. }
  63. }
  64. );
  65. }
  66. }
  67. }