1

I am currently getting an 'ObjectDisposed' exception, and I'm not sure how to resolve it. I have made sure I am checking that the stream is not closed before I begin the read operation:

token.ThrowIfCancellationRequested();
int amount = await stream.ReadAsync(buffer, offset, buffer.Length - offset, token);

Before I close the stream, I cancel any pending reads:

tokenSource.Cancel();
stream.Close();

However, I am still getting the below exception:

Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.

This is spurious, so it appears to be a race condition, but it happens frequently enough for me to reproduce it. There seems to be three possibilities:

  • CancellationTokenSource is not atomic (A quick google did not answer this)
  • NetworkStream gives being disposed higher priority than being cancelled
  • Some other reason that I am missing

How can I handle this more gracefully? Keep in mind the following restrictions I'm currently working with:

  • The stream is being used in a long-lived wrapper class, which may not be in a using block
  • The stream is from a socket wrapped by a NetworkStream
  • The cancellation token is made from a linked token source
Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
  • Show your whole block of code so we can assess this issue better – jegtugado Dec 18 '17 at 01:05
  • 1
    IIRC cancelling of a stream read isn't actually implemented. I might be wrong. Searching for evidence... – spender Dec 18 '17 at 01:11
  • 1
    Yes.. I remember correctly. Read (and weep): https://stackoverflow.com/questions/20131434/cancel-networkstream-readasync-using-tcplistener – spender Dec 18 '17 at 01:13
  • An interesting article for you: https://blogs.msdn.microsoft.com/pfxteam/2012/10/05/how-do-i-cancel-non-cancelable-async-operations/ – spender Dec 18 '17 at 01:19
  • Oh damn. Thanks @spender, I never would have found that otherwise. So I guess I need to catch ObjectDisposedException, and check the cancellation token there – Andrew Williamson Dec 18 '17 at 01:19
  • IKR? The fake cancellation is particularly irksome to me. Toub's article that I posted above looks like another option... – spender Dec 18 '17 at 01:20

0 Answers0