Gets an ObjectDisposed exception when calling Shutdown, then Close on Socket

I have a SocketState object that I use to wrap a buffer and socket together and pass it for use with socket methods like Begin / End async. In the destructor, I have this:

~SocketState()
{
    if (!_socket.Connected) return;

    _socket.Shutdown(SocketShutdown.Both);
    _socket.Close();
}

When it comes to Close (), I get an ObjectDisposed exception. If I comment on the Shutdown () call, I don't get an error when it gets into the Close () method. What am I doing wrong?

Edit:

I know that the IDisposable solution is similar to how my code should be laid out, but this does not actually solve my problem. It doesn't look like the destructor gets called twice, so why not call the dispose () call instead of using the destructor? I still get the same exception when you call these 2 functions in a row.

, , , 2 try . , , ( ), , .

+3
3

_socket IDisposable, , ( ).

IDisposable .

:

public class SocketState : IDisposable
{
  Socket _socket;

  public SocketState()
  {
    _socket = new Socket();
  }

  public bool IsDisposed { get; private set; }

  public void SomeMethod()
  {
    if (IsDisposed)
      throw new ObjectDisposedException("SocketState");

    // Some other code
  }

  #region IDisposable Members

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing)
  {
    if (!IsDisposed)
    {
      if (disposing)
      {
        if (_socket != null)
        {
          _socket.Close();
        }
      }

      // disposed unmanaged resources

      IsDisposed = true;
    }
  }

  ~SocketState()
  {
    Dispose(false);
  }

  #endregion
}
+2

; , Close() Dispose() Socket ( ). Shutdown(), ws2_32.dll!shutdown() , Dispose(). , ws2_32.dll!shutdown() .

, Close().

+3

. ,

Close(), ObjectDisposedException

, Close . Shutdown, ObjectDisposedException. , Shutdown out - , .

, .Dispose() 'd ( ) , .

As said here :

The execution order of finalizers is not deterministic - in other words, you cannot rely on another object that is still available in your finalizer.

0
source

Source: https://habr.com/ru/post/1704390/


All Articles