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.Threading;
  5. namespace System.Reactive.Linq
  6. {
  7. public partial class AsyncObservable
  8. {
  9. public static IAsyncObservable<TSource> Synchronize<TSource>(this IAsyncObservable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return Create(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.Synchronize(observer)));
  14. }
  15. public static IAsyncObservable<TSource> Synchronize<TSource>(this IAsyncObservable<TSource> source, AsyncLock gate)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. if (gate == null)
  20. throw new ArgumentNullException(nameof(gate));
  21. return Create(
  22. source,
  23. gate,
  24. default(TSource),
  25. (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 AsyncLock());
  35. }
  36. public static IAsyncObserver<TSource> Synchronize<TSource>(IAsyncObserver<TSource> observer, AsyncLock 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. }