Range.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. ct.ThrowIfCancellationRequested();
  39. for (int i = start, end = start + count - 1; i <= end && !ct.IsCancellationRequested; i++)
  40. {
  41. await observer.OnNextAsync(i).RendezVous(scheduler, ct);
  42. }
  43. ct.ThrowIfCancellationRequested();
  44. await observer.OnCompletedAsync().RendezVous(scheduler, ct);
  45. });
  46. }
  47. }
  48. }