using System.Threading.Tasks;
using System.Collections.Generic;
public static async Task Main()
var cancellationTokenSource = new CancellationTokenSource();
await foreach(var item in GetValues3(5, 3).WithCancellation(cancellationTokenSource.Token).ConfigureAwait(false))
static async IAsyncEnumerable<int> GetValues1()
await Task.Delay(500).ConfigureAwait(false);
await Task.Delay(500).ConfigureAwait(false);
await Task.Delay(500).ConfigureAwait(false);
static async IAsyncEnumerable<int> GetValues2(int start, int count)
for(var counter = start; counter < start + count; counter++)
await Task.Delay(500).ConfigureAwait(false);
static MyAsyncEnumerable GetValues3(int start, int count)
public MyAsyncEnumerable(int start, int count)
=> (this.start, this.count) = (start, count);
public Enumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
=> new(start, count, cancellationToken);
IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(CancellationToken cancellationToken)
=> new Enumerator(start, count, cancellationToken);
readonly CancellationToken cancellationToken;
public Enumerator(int start, int count, CancellationToken cancellationToken)
=> (end, this.cancellationToken, current) = (start + count, cancellationToken, start - 1);
public async ValueTask<bool> MoveNextAsync()
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(500, cancellationToken).ConfigureAwait(false);
public ValueTask DisposeAsync()