Skip to content

Instantly share code, notes, and snippets.

@kkozmic
Created December 11, 2010 04:12
Show Gist options
  • Save kkozmic/737140 to your computer and use it in GitHub Desktop.
Save kkozmic/737140 to your computer and use it in GitHub Desktop.
Is this 100% thread safe way of making sure base.Release is only ever *ever* called once?
private Object instance;
public override void Dispose()
{
var localInstance = instance;
if (localInstance == null)
{
return;
}
// we're trying to atomically replace the instance with null.
var originalValue = Interlocked.CompareExchange(ref instance, null, localInstance);
if (originalValue == null)
{
// some other thread was quicker.
return;
}
// ok, do regardless of other threads, it looks like I'm the one to have nullified the instance.
// it is my responsibility to finish the job while all other threads go home.
base.Release(originalValue);
}
@bling
Copy link

bling commented Dec 11, 2010

yes it's thread safe. it can be much simpler with this tho:

        var original = Interlocked.Exchange(ref instance, null);
        if (original != null)
        {
            base.Release(original);
        }

@kkozmic
Copy link
Author

kkozmic commented Dec 11, 2010

thanks bling,

I'm doing the additional check at the beginning to save a few cycles. You're probably right though that several nanoseconds are not worth the additional clutter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment