Home > Net >  How check dispose in C#
How check dispose in C#

Time:11-13

I want to check dispose in all methods:

public class WebSocketClient : IDisposable
{
    private ClientWebSocket _socket;
    private bool _isDisposed;
    //methods
    public void SetBuffer(int receiveBufferSize, int sendBufferSize) =>
            _socket.Options.SetBuffer(receiveBufferSize, sendBufferSize); //How check dispose?
    //other methods
    protected virtual void Dispose(bool disposing)
    {
        if (!_isDisposed)
        {
            if (disposing)
            {
                _socket.Dispose();
            }
            _isDisposed = true;
        }
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

I added methods to check dispose and run acrion if object is not disposed:

public async Task CallWithCheckDispose(Func<Task> func)
{    
    if (!_isDisposed)
        await func.Invoke();    
    else
        throw new ObjectDisposedException(GetType().Name);
}
public async Task CallWithCheckDispose(Action func)
{    
    if (!_isDisposed)
        func.Invoke();    
    else
        throw new ObjectDisposedException(GetType().Name);
}

And use it:

public async Task SetBuffer(int receiveBufferSize, int sendBufferSize) =>
    await CallWithCheckDispose(() =>
        _socket.Options.SetBuffer(receiveBufferSize, sendBufferSize);
    );

But I think what this is not best solution Is there other solution?

CodePudding user response:

You can use a helper method, like so:

private void checkDisposed() {
  if (_isDisposed) {
    throw new ObjectDisposedException();
  }
}

Then, in each of your other methods:

public async Task CallWithCheckDispose(Func<Task> func)
{
  checkDisposed();
  await func.Invoke();
}
  • Related