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
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.