Skip to content

Instantly share code, notes, and snippets.

@aalmada
Created May 11, 2021 12:47
Show Gist options
  • Save aalmada/feaf0af484b669d0ab385abed37e3aa3 to your computer and use it in GitHub Desktop.
Save aalmada/feaf0af484b669d0ab385abed37e3aa3 to your computer and use it in GitHub Desktop.
public static async ValueTask<int> CountAsync<TEnumerable, TEnumerator, TSource>(this TEnumerable source, CancellationToken cancellationToken = default)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
{
var counter = 0;
var enumerator = source.GetAsyncEnumerator(cancellationToken);
try
{
checked
{
while (await enumerator.MoveNextAsync().ConfigureAwait(false))
counter++;
}
}
finally
{
await enumerator.DisposeAsync().ConfigureAwait(false);
}
return counter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment