I expected to be able to start another read operation if I cancel the current read with CancelPendingRead
. But this code throws a InvalidOperationException
. Does CancelPendingRead
not work as i think or what could be the problem?
I'm testing with .Net Core 3.1.
try
{
var p = new Pipe();
await p.Writer.WriteAsync( new Byte[] { 1, 2, 3 } );
var rr = await p.Reader.ReadAsync();
p.Reader.CancelPendingRead();
rr = await p.Reader.ReadAsync(); // Reading is already in progress.
}
catch ( InvalidOperationException ex )
{
Console.WriteLine( ex );
}
Ok I found the problem:
CancelPendingRead
does cancel a waiting read. It does NOT not "cancel" a already executed read. The solution is to advance the reader to the start of the just read buffer.
var p = new Pipe();
var readTask = p.Reader.ReadAsync();
p.Reader.CancelPendingRead();
var rr = await readTask;
// rr.IsCanceled; => is true
p.Reader.AdvanceTo( rr.Buffer.Start );
rr = await p.Reader.ReadAsync();