Synchronize.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. using System.Threading;
  5. namespace System.Reactive.Linq
  6. {
  7. 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<TSource>(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<TSource>(observer => source.SubscribeSafeAsync(AsyncObserver.Synchronize(observer, gate)));
  22. }
  23. }
  24. partial class AsyncObserver
  25. {
  26. public static IAsyncObserver<TSource> Synchronize<TSource>(IAsyncObserver<TSource> observer)
  27. {
  28. if (observer == null)
  29. throw new ArgumentNullException(nameof(observer));
  30. return Synchronize(observer, new AsyncLock());
  31. }
  32. public static IAsyncObserver<TSource> Synchronize<TSource>(IAsyncObserver<TSource> observer, AsyncLock gate)
  33. {
  34. if (observer == null)
  35. throw new ArgumentNullException(nameof(observer));
  36. if (gate == null)
  37. throw new ArgumentNullException(nameof(gate));
  38. return Create<TSource>(
  39. async x =>
  40. {
  41. using (await gate.LockAsync().ConfigureAwait(false))
  42. {
  43. await observer.OnNextAsync(x).ConfigureAwait(false);
  44. }
  45. },
  46. async ex =>
  47. {
  48. using (await gate.LockAsync().ConfigureAwait(false))
  49. {
  50. await observer.OnErrorAsync(ex).ConfigureAwait(false);
  51. }
  52. },
  53. async () =>
  54. {
  55. using (await gate.LockAsync().ConfigureAwait(false))
  56. {
  57. await observer.OnCompletedAsync().ConfigureAwait(false);
  58. }
  59. }
  60. );
  61. }
  62. }
  63. }