Can I cancel StreamReader.ReadLineAsync with a CancellationToken?

.NET 6 brings Task.WaitAsync(CancellationToken). So one can write:

using StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{       
    Console.WriteLine(await reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false));
}

In .NET 7 (not yet released), it should be possible to write simply:

using StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{       
    Console.WriteLine(await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
}

based on https://github.com/dotnet/runtime/issues/20824 and https://github.com/dotnet/runtime/pull/61898.

Leave a Comment