runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Add CancellationToken to StreamReader.Read* methods

Open ChadNedzlek opened this issue 9 years ago • 32 comments

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.

ChadNedzlek avatar Mar 29 '17 21:03 ChadNedzlek

This raises some obvious questions... I guess I'll be the one to ask them.

  1. Should this go as high as System.IO.TextReader?
    1. 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.
    2. On the plus side, it looks like the concerns I have re: System.IO.TextReader actually don't necessarily apply to System.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).
  2. Should this also apply to System.IO.StreamWriter?
    1. 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.

airbreather avatar Sep 13 '17 12:09 airbreather

@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.

ChadNedzlek avatar Sep 14 '17 01:09 ChadNedzlek

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?

JeremyKuhne avatar Oct 12 '17 22:10 JeremyKuhne

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.

stephentoub avatar Oct 13 '17 00:10 stephentoub

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[]?

JeremyKuhne avatar Oct 13 '17 00:10 JeremyKuhne

Right.

stephentoub avatar Oct 13 '17 00:10 stephentoub

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 avatar Sep 05 '18 16:09 narciero

@narciero Just needs someone to drive updating the proposal. Feedback is:

  1. Should target TextReader
  2. Should only update ReadToEnd and ReadLine
  3. Should follow the same implementation pattern as ReadAsync(Memory<char>) (including overrides in StreamReader and StringReader)

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.

JeremyKuhne avatar Sep 05 '18 18:09 JeremyKuhne

I'd also like to see CancellationTokens implemented for these methods. The above feedback sounds good.

Shane32 avatar Mar 26 '20 17:03 Shane32

@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.

ChadNedzlek avatar Mar 31 '20 21:03 ChadNedzlek

Unless ReadAsync is somehow covered by some other changes, and now has a cancellable version.

Yeah, there's now TextReader.ReadAsync(Memory<char>, CancellationToken)

bartonjs avatar Mar 31 '20 21:03 bartonjs

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. :-)

ChadNedzlek avatar Mar 31 '20 21:03 ChadNedzlek

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 ReadAsync and ReadBlockAsync as they seem to be covered by the new Memory<byte>-based overloads.
  • Changed the return type to ValueTask
  • Added nullable annotations

Any chance this might get into a review anytime soon?

khellang avatar Jan 13 '21 08:01 khellang

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?

orthoxerox avatar May 13 '21 17:05 orthoxerox

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.

airbreather avatar May 13 '21 18:05 airbreather

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.

Shane32 avatar May 13 '21 19:05 Shane32

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 avatar May 13 '21 20:05 orthoxerox

@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.

lichti81 avatar Jul 08 '21 10:07 lichti81

@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.

huoyaoyuan avatar Dec 14 '21 10:12 huoyaoyuan

@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)
}

adamsitnik avatar Jan 17 '22 08:01 adamsitnik