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

前端 未结 6 2071
别跟我提以往
别跟我提以往 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:34

    Most BCL implementations of Dispose are not thread-safe. The idea is that it's up to the caller of Dispose to make sure nobody else is using the instance anymore before it is Disposed. In other words, it pushes the synchronization responsibility upwards. This makes sense, as otherwise now all your other consumers need to handle the boundary case where the object was Disposed while they were using it.

    That said, if you want a thread-safe Disposable class, you can just create a lock around every public method (including Dispose) with a check for _disposed at the top. This may become more complicated if you have long-running methods where you don't want to hold the lock for the entire method.

提交回复
热议问题