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