Skip to content

Commit 82a2cda

Browse files
authored
Clean up silly attempt at thread-safety in NetworkStream.Dispose (dotnet#46997)
1 parent 2c1cb08 commit 82a2cda

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ public class NetworkStream : Stream
2222
// Used by the class to indicate that the stream is writable.
2323
private bool _writeable;
2424

25+
// Whether Dispose has been called. 0 == false, 1 == true
26+
private int _disposed;
27+
2528
// Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket.
2629
public NetworkStream(Socket socket)
2730
: this(socket, FileAccess.ReadWrite, ownsSocket: false)
@@ -337,13 +340,15 @@ public void Close(int timeout)
337340
_closeTimeout = timeout;
338341
Dispose();
339342
}
340-
private volatile bool _disposed;
343+
341344
protected override void Dispose(bool disposing)
342345
{
343-
// Mark this as disposed before changing anything else.
344-
bool disposed = _disposed;
345-
_disposed = true;
346-
if (!disposed && disposing)
346+
if (Interlocked.Exchange(ref _disposed, 1) != 0)
347+
{
348+
return;
349+
}
350+
351+
if (disposing)
347352
{
348353
// The only resource we need to free is the network stream, since this
349354
// is based on the client socket, closing the stream will cause us
@@ -664,7 +669,7 @@ internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool sile
664669

665670
private void ThrowIfDisposed()
666671
{
667-
if (_disposed)
672+
if (_disposed != 0)
668673
{
669674
ThrowObjectDisposedException();
670675
}

0 commit comments

Comments
 (0)