In process of developing I often face with the next problem: if some method is already executed by one thread – method is must not be executed by another thread. Another thread must do nothing – simple exit from method, beacuse of it I can’t use “lock”. Usually, I solve this problem like that:
private bool _isSomeMethodExecuted = false;
public void SomeMethod ()
{
if (!this._isSomeMethodExecuted) //check if method is already executed
{
this._isSomeMethodExecuted = true;
//Main code of method
this._isSomeMethodExecuted = false;
}
}
But this code is not thread-safe: if one thread execute condition statement but It be stopped before set flag in true and another thread can execute condition – then both threads are inside method code.
Is there any thread-safe replace for it?
the following is thread-safe and does not block if the method is already executing – even if it is alreasy executing on the same thread… which provides protection from reentrancy for all scenarios.
For refrences see http://msdn.microsoft.com/en-us/library/zs86dyzy.aspx