Range.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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.Reactive.Concurrency;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Linq
  7. {
  8. partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<int> Range(int start, int count)
  11. {
  12. if (count < 0 || ((long)start) + count - 1 > int.MaxValue)
  13. throw new ArgumentOutOfRangeException(nameof(count));
  14. return Create<int>(observer => AsyncObserver.Range(observer, start, count));
  15. }
  16. public static IAsyncObservable<int> Range(int start, int count, IAsyncScheduler scheduler)
  17. {
  18. if (count < 0 || ((long)start) + count - 1 > int.MaxValue)
  19. throw new ArgumentOutOfRangeException(nameof(count));
  20. if (scheduler == null)
  21. throw new ArgumentNullException(nameof(scheduler));
  22. return Create<int>(observer => AsyncObserver.Range(observer, start, count, scheduler));
  23. }
  24. }
  25. partial class AsyncObserver
  26. {
  27. public static Task<IAsyncDisposable> Range(IAsyncObserver<int> observer, int start, int count) => Range(observer, start, count, TaskPoolAsyncScheduler.Default);
  28. public static Task<IAsyncDisposable> Range(IAsyncObserver<int> observer, int start, int count, IAsyncScheduler scheduler)
  29. {
  30. if (observer == null)
  31. throw new ArgumentNullException(nameof(observer));
  32. if (count < 0 || ((long)start) + count - 1 > int.MaxValue)
  33. throw new ArgumentOutOfRangeException(nameof(count));
  34. if (scheduler == null)
  35. throw new ArgumentNullException(nameof(scheduler));
  36. return scheduler.ScheduleAsync(async ct =>
  37. {
  38. if (ct.IsCancellationRequested)
  39. return;
  40. for (int i = start, end = start + count - 1; i <= end && !ct.IsCancellationRequested; i++)
  41. {
  42. await observer.OnNextAsync(i).RendezVous(scheduler, ct);
  43. }
  44. if (ct.IsCancellationRequested)
  45. return;
  46. await observer.OnCompletedAsync().RendezVous(scheduler, ct);
  47. });
  48. }
  49. }
  50. }