Created
December 11, 2010 04:12
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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
yes it's thread safe. it can be much simpler with this tho: