1

I am trying to add a "timeout" for the ReadAsync method from a NetworkStream.

I want to cancel the ReadAsync after a specific time.

For example:

ctsTimeout.CancelAfter(10);

int bytesRead = await nsStream.ReadAsync(newArr, 0, newArr.Length, ctsTimeout.Token);

But the method is still waiting for a response from the server.

Is it possible to cancel this method in its reading state?

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Gerry Seel
  • 63
  • 7
  • The main issue I have with this is cleanup after a ReadAsync or WriteAsync completes. If I dispose of a class that contains the read/write buffer too early, an illegal operation can occur. Don't dispose of the class, and you may wind up with a memory leak. I remedied this by adding Dispose( ) to the Read/Write Task using ContinueWith(() => classThatHoldsTheBuffer.Dispose()). – Brain2000 Jul 22 '19 at 01:43

1 Answers1

2

NetworkStream (or Stream by inheritance) doesn't really support cancellation. The ReadAsync method accepts a cancellation token, sure; but that really just allows you to know if a cancellation was requested before the read completed. The ReadAsync really just wraps BeginRead and EndRead--which offer no way to cancel the read operation.

To really cancel a read you need to dispose or Close the NetworkStream object.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98