What is the correct way of adding thread-safety to an IDisposable object?

前端 未结 6 2067
别跟我提以往
别跟我提以往 2021-01-31 16:22

Imagine an implementation of the IDisposable interface, that has some public methods.

If an instance of that type is shared between multiple threads and o

6条回答
  •  温柔的废话
    2021-01-31 16:41

    FWIW, your sample code matches how my co-workers and I typically deal with this issue. We generally define a private CheckDisposed method on the class:

    private volatile bool isDisposed = false; // Set to true by Dispose
    
    private void CheckDisposed()
    {
        if (this.isDisposed)
        {
            throw new ObjectDisposedException("This instance has already been disposed.");
        }
    }
    

    Then we call the CheckDisposed() method at the top of all public methods.

    If thread contention over disposal is considered likely, rather than an error condition, I will also add a public IsDisposed() method (Similar to Control.IsDisposed).


    Update: Based on the comments with respect to the value of making isDisposed volatile, note that the "fence" issue is rather trivial given how I use the CheckDisposed() method. It is essentially a troubleshooting tool for quickly catching the case where code calls a public method on the object after it has already been disposed. Calling CheckDisposed() at the start of a public method in no way guarantees that the object won't be disposed within that method. If I consider that to be a risk inherent in my class's design, as opposed to an error condition I failed to account for, then I use the aforementioned IsDisposed method along with appropriate locking.

提交回复
热议问题