Skip to content

Commit

Permalink
Clean up silly attempt at thread-safety in NetworkStream.Dispose (dot…
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub authored Jan 14, 2021
1 parent 2c1cb08 commit 82a2cda
Showing 1 changed file with 11 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ public class NetworkStream : Stream
// Used by the class to indicate that the stream is writable.
private bool _writeable;

// Whether Dispose has been called. 0 == false, 1 == true
private int _disposed;

// Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket.
public NetworkStream(Socket socket)
: this(socket, FileAccess.ReadWrite, ownsSocket: false)
Expand Down Expand Up @@ -337,13 +340,15 @@ public void Close(int timeout)
_closeTimeout = timeout;
Dispose();
}
private volatile bool _disposed;

protected override void Dispose(bool disposing)
{
// Mark this as disposed before changing anything else.
bool disposed = _disposed;
_disposed = true;
if (!disposed && disposing)
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}

if (disposing)
{
// The only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
Expand Down Expand Up @@ -664,7 +669,7 @@ internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool sile

private void ThrowIfDisposed()
{
if (_disposed)
if (_disposed != 0)
{
ThrowObjectDisposedException();
}
Expand Down

0 comments on commit 82a2cda

Please sign in to comment.