Basically I want to make sure a field in a class (in this case the _changedPoller) is Disposed as early as possible when not needed anymore. I call StopChangedPolling in the class' Dispose method and when certain events occur. What is the best, thread safe way to dispose a field only once? Is the following code ok?
private void StopChangedPolling()
{
IDisposable changedPoller = Interlocked.CompareExchange(ref _changedPoller, null, _changedPoller);
if (changedPoller != null)
changedPoller.Dispose();
}
The second time this is called, _changedPoller is null and no exception is thrown, even though the documentation states that an ArgumentNullException is thrown if the address of location1 is a null pointer.