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

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

    I prefer to use integers and Interlocked.Exchange or Interlocked.CompareExchange on an integer-type object "disposed" or "state" variable; I'd use enum if Interlocked.Exchange or Interlocked.CompareExchange could handle such types, but alas they cannot.

    One point which most discussions of IDisposable and finalizers fail to mention is that while an object's finalizer shouldn't run while IDisposable.Dispose() is in progress, there's no way for a class to prevent objects of its type from being declared dead and then resurrected. To be sure, if outside code allows that to happen there obviously can't be any requirement that the object "work normally", but the Dispose and finalize methods should be well-enough protected to ensure that they won't corrupt any other objects' state, which will in turn generally require using either locks or Interlocked operations on object state variables.

提交回复
热议问题