Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How check dispose in C#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading