Add CancellationToken to StreamReader.Read* methods
EDIT: link to updated proposal: https://github.com/dotnet/runtime/issues/20824#issuecomment-1014246524
Today we have the following methods on StreamReader:
public class StreamReader
{
public Task<string> ReadLineAsync();
public Task<string> ReadToEndAsync();
public Task<int> ReadAsync(char[] buffer, int index, int count);
public Task<int> ReadBlockAsync(char[] buffer, int index, int count);
}
None of these support cancellation via CancellationTokens, even though the underlying Stream ReadAsync API's do
Proposed API
Add the following methods
public class StreamReader
{
public Task<string> ReadLineAsync(CancellationToken token);
public Task<string> ReadToEndAsync(CancellationToken token);
public Task<int> ReadAsync(char[] buffer, int index, int count, CancellationToken token);
public Task<int> ReadBlockAsync(char[] buffer, int index, int count, CancellationToken token);
}
Motivation
Since these methods read from an underlying stream that may have long delays before data is available, they can block for long periods of time. Especially if the underlying stream is network based.
When trying to create a responsive application in these circumstances, where long running operations that might never return can be cancelled to return control back to the user, the inability to cancel these operations in difficult.
Currently the only real option is to fork the call into a fake cancellable operation that ends up ignoring original Task when a cancellation happens, with something like ThreadingTools.WithCancellation. But that leaves the reading Task (and potentially the stream and any continuations registered on it) floating, unreferenced.
This raises some obvious questions... I guess I'll be the one to ask them.
- Should this go as high as
System.IO.TextReader?- It seems like bolting this on there, at least in a way that's similar to how I would design it if cancellation were supported from the beginning (i.e., subclasses can only override a method that has cancellation support), would be either a breaking change or a confusing API.
- On the plus side, it looks like the concerns I have re:
System.IO.TextReaderactually don't necessarily apply toSystem.IO.StreamReader. The latter already uses blocks like this to explicitly account for subclasses, so a subclass just might not get the benefits of cancellation support by calling base (much like they don't get all the benefits of async support today by calling base).
- Should this also apply to
System.IO.StreamWriter?- If so, everything in my previous bullet point also applies to that side of things... here's a block that's similar to the one I linked for
System.IO.StreamReader.
- If so, everything in my previous bullet point also applies to that side of things... here's a block that's similar to the one I linked for
@airbreather In regards to dotnet/corefx#2, in my opinion, it's slightly less important for the Writer side of things, since it's a less common scenario to be blocked forever on a Write that will never finish, and you now can't cancel out of. At least... as far as my imagination can take me down that route.
Though it probably makes sense to add them there too, for consistency sake, and I'm sure there is some networking scenario where you are blocked on a write operation somehow that you'd want to cancel.
We just added CancellationToken support to TextReader with our new Span APIs. https://github.com/dotnet/corefx/pull/24434
@stephentoub Any comments on adding the cancellation token support for the existing methods?
Any comments on adding the cancellation token support for the existing methods?
The new Memory-based overload we've added take care of ReadAsync and ReadBlockAsync; there's no need to add additional overloads for those.
They don't cover ReadLineAsync or ReadToEndAsync, so we could still choose to add cancelable overloads for those.
The new Memory-based overload we've added take care of ReadAsync and ReadBlockAsync; there's no need to add additional overloads for those.
So rely on wrapping the array rather than add an overload for char[]?
Right.
any update on adding cancellation token overloads to ReadLineAsync ?
This is a common use case for reading data from a streaming HTTP API via HttpContentStream, would be nice to be able to set a timeout per read
@narciero Just needs someone to drive updating the proposal. Feedback is:
- Should target
TextReader - Should only update
ReadToEndandReadLine - Should follow the same implementation pattern as
ReadAsync(Memory<char>)(including overrides inStreamReaderandStringReader)
Another question that should be considered is how a lower allocation version of these two APIs could/should be implemented. It might make more sense for these to return (and possibly take) StringBuilder, for example (potentially eliminating allocations). And/or it may be useful to have a TryRead* that takes a Memory<char> buffer.
I'd also like to see CancellationTokens implemented for these methods. The above feedback sounds good.
@JeremyKuhne If it's only ReadLine and ReadToEndAsync, this doesn't actually cover the scenario that was blocking me that caused me to open this issue. Unless ReadAsync is somehow covered by some other changes, and now has a cancellable version.
Unless ReadAsync is somehow covered by some other changes, and now has a cancellable version.
Yeah, there's now TextReader.ReadAsync(Memory<char>, CancellationToken)
That's good to hear. I should be able to rearrange my pile of inherited Streams/StreamReaders to be able to take advantage of that... but I still need the other methods. :-)
Here's an updated proposal based on the feedback above:
public abstract class TextReader
{
public virtual ValueTask<string?> ReadLineAsync(CancellationToken token);
public virtual ValueTask<string> ReadToEndAsync(CancellationToken token);
}
The following changes have been made:
- Moved the methods up to
TextReader - Removed
ReadAsyncandReadBlockAsyncas they seem to be covered by the newMemory<byte>-based overloads. - Changed the return type to
ValueTask - Added nullable annotations
Any chance this might get into a review anytime soon?
I understand that the new methods must be virtual to ensure backward compatibility, but there's just no sensible default implementation of TextReader.ReadLineAsync(CancellationToken) I can come up with. I could just make it ignore the token, of course, since StringReader doesn't really require cancellation and StreamReader gets its own implementation, but it would make me feel dirty. Does it really have to go on TextReader? What are the use cases?
Does it really have to go on
TextReader? What are the use cases?
A caller may have a TextReader that may or may not be a StreamReader (or similar), and they have a CancellationToken that they would be happy to pass through if it's supported. Whenever it's a StreamReader, they want to be able to cancel the pending read, but for StringReader (or similar), they're fine with the read completing, since it's strictly synchronous anyway.
An actual, specific, real-world use case I do not have, but it would be really awkward for all callers to have to write this:
switch (someTextReader)
{
case StreamReader someStreamReader:
return await someStreamReader.ReadLineAsync(cancellationToken);
default:
return await someTextReader.ReadLineAsync();
}
So writing virtual methods on TextReader whose base implementations accept and ignore a CancellationToken will definitely be weird here, but IMO it's not actually that bad, and it seems to meet the strict compatibility requirements of .NET, so I support it.
The existing default implementations of cancelable asynchronous methods (e.g. ReadAsync(Memory<Char>, CancellationToken)) currently start a new thread and synchronously read the data from that thread. Attempting to cancel with the cancellation token only cancels the read if the cancel request occurs before the thread is allocated. Once the synchronous read has begun, it completes synchronously. This makes sense given the scenario. The same logic would apply to a default implementation of ReadLineAsync(CancellationToken):
public virtual Task<string?> ReadLineAsync(CancellationToken cancellationToken) =>
Task<string?>.Factory.StartNew(static state => ((TextReader)state!).ReadLine(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
For reference, see the existing default implementation of ReadLineAsync() here:
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs#L206..L208
For a truly asynchronous implementation, StreamReader must override the method and utilize asynchronous reads to the underlying stream. StringReader would likely not override the method at all, relying on the default implementation shown above.
An actual, specific, real-world use case I do not have
We can come up with one easy - how about a CSV data parser? The method may be defined as ValueTask<T> ReadRow<T>(TextReader reader, CancellationToken token = default). It relies on ReadLineAsync(CancellationToken cancellationToken) to read a row of text, and then parses it into columns and ultimately somehow into T -- perhaps by examining the first row and matching header names to property names. This is a simple use case of ReadLineAsync(CancellationToken) where the cancellation token should pass through to the underlying TextReader. It should be noted that this could be much faster code than attempting to work around the limitation by calling ReadAsync(Memory<char>, CancellationToken) repeatedly one character at a time, since the underlying StreamReader could potentially examine its underlying buffer to directly scan for newline tokens.
While it is certainly possible to add the asynchronous overload directly to StreamReader, I would say that the method belongs on TextReader along with the other existing asynchronous methods. It would certainly be unfortunate if we ended up in a scenario similar to IQueryable or IDbConnection where there is no standard for asynchronous methods.
The changes to the classes do not look too threatening (although they haven't been tested yet), so the API review is probably a bigger blocker.
@orthoxerox: I think there are more changes necessary Lets assume the client usually do following:
StreamReader reader = ...
while (!reader.EndOfStream)
{
await reader.ReadLineAsync();
...
}
A short look at the implementation of EndOfStream shows me that there is the stream read into cache. This means when it comes to ReadLineAsync it is already to late, because there the info from cache is read to identify lines in text.
I think to be able to support cancelation following is needed:
StreamReader reader = ...
while (!await reader.IsEndOfStreamAsync(cancelationToken))
{
await reader.ReadLineAsync(cancelationToken);
...
}
But I'm not a expert. I just invested a view minutes for check of code.
A possible alternative would be to provide and implement a own class which supports asynchron stream reading with cancelation.
As somebody was asking for a usecase. Here is one:
When you want like to implement server side events with ASP.NET Core you generate streams on server which you need to read as stream on client. There could be a long time (minutes or hours) between two junks of information dropping in on client side.
During this time the client hangs in the reader.EndOfStream, because there it is waiting for new content from the server.
A use of cancelation is not possible at the moment as the stream reader is not able to cancel the wait for new content.
Edit: It seems to be that the Grpc team had the same problem in the past. Therefore they defined and implemented a HttpContentClientStreamReader hidden behind interface IAsyncStreamReader. Please take a look at interface documentation to see how it behaves. After some hops the implementation lands in ReadMessageAsync extension method which uses Stream.ReadAsync to read with cancelation the values out of stream.
@dotnet/area-system-io I think it's worth to require a revisit since it's blocking other APIs. We should be also aware of the stream changes in 6.0.
@khellang thank you for updating the proposal (https://github.com/dotnet/runtime/issues/20824#issuecomment-759281692) !
I don't think that ReadToEndAsync should return a ValueTask (it allocates a LOT of memory since it reads the file to the end)
Here is the proposal that I would like to present to the review board:
public abstract class TextReader
{
public virtual Task<string?> ReadLineAsync()
+ public virtual ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken)
public virtual Task<string> ReadToEndAsync()
+ public virtual Task<string> ReadToEndAsync(CancellationToken cancellationToken)
}