I have a method, which must be called no more than once, for example, Dispose. Now, I realize It as next:
private bool _isAlive = true;
public void Dispose()
{
if (this._isAlive)
{
this._isAlive = false;
//Do Something
}
}
But It is not thread-safe because there is a gap between comprasion and setting flag _isAlive to false. So, It is possible that more than one thread execute //Do Something code.
Is there thread-safe variant of it?
use (updated according to comments):
For refrences see http://msdn.microsoft.com/en-us/library/zs86dyzy.aspx
UPDATE (as per comment from @LukeH):
A single
CompareExchangecall is simpler/better: