public static async Task ForEachAsync <T>(this IAsyncEnumerable <T> source, Func <T, Task> body) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (body == null) { throw new ArgumentNullException(nameof(body)); } IAsyncEnumerator <T> e = source.GetAsyncEnumerator(); try { while (await e.WaitForNextAsync().ConfigureAwait(false)) { while (true) { T item = e.TryGetNext(out bool success); if (!success) { break; } await body(item).ConfigureAwait(false); } } } finally { await e.DisposeAsync().ConfigureAwait(false); } }
public async Task <bool> WaitForNextAsync() { var id = Interlocked.Increment(ref counter); Console.WriteLine($"[{label}] {this.id}:{id}> WaitForNextAsync - Start"); var res = await enumerator.WaitForNextAsync().ConfigureAwait(false); Console.WriteLine($"[{label}] {this.id}:{id}> WaitForNextAsync - Stop({res})"); return(res); }
public static async Task ForEachAsync <T>(this IAsyncEnumerable <T> source, Func <T, CancellationToken, Task> body, CancellationToken cancellationToken = default(CancellationToken)) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (body == null) { throw new ArgumentNullException(nameof(body)); } cancellationToken.ThrowIfCancellationRequested(); IAsyncEnumerator <T> e = source.GetAsyncEnumerator(); try { while (await e.WaitForNextAsync().ConfigureAwait(false)) { while (true) { cancellationToken.ThrowIfCancellationRequested(); T item = e.TryGetNext(out bool success); if (!success) { break; } await body(item, cancellationToken).ConfigureAwait(false); } } } finally { await e.DisposeAsync().ConfigureAwait(false); } }
static async Task Main() { IAsyncEnumerable <int> test = AsyncIterator(); IAsyncEnumerator <int> enumerable = test.GetAsyncEnumerator(); //foreach await (var value in enumerable) //{ // Console.WriteLine(value) //} while (await enumerable.WaitForNextAsync()) { while (true) { int value = enumerable.TryGetNext(out bool success); if (!success) { goto outer_loop_continue; } Console.WriteLine(value); } outer_loop_continue :; } }
public Task <bool> WaitForNextAsync() { watch.Report("WaitForNextAsync"); return(enumerator.WaitForNextAsync()); }
public ConfiguredTaskAwaitable <bool> WaitForNextAsync() => _enumerator.WaitForNextAsync().ConfigureAwait(_continueOnCapturedContext);