Is it theoretically possible that something will interrupt a .NET thread (e.g. a ThreadAbortException) between the return of a method and the assignment of its return value to a local?
For example, is this following code safe or is it possible that myMutex.WaitOne() acquires the mutex and returns true, but an exception is thrown before that value true is assigned to mutexAcquired and therefore the acquired mutex is not released?
bool mutexAcquired = false;
try
{
mutexAcquired = myMutex.WaitOne(1000);
if (!mutexAcquired)
throw new Exception();
// OK, do some stuff...
}
finally
{
if (mutexAcquired)
myMutex.ReleaseMutex();
}
If that is safe, then what about the following code?
if (!myMutex.WaitOne(1000))
throw new Exception();
try
{
// OK, do some stuff...
}
finally
{
myMutex.ReleaseMutex();
}
Again, is it possible for myMutex.WaitOne() to return true, but for ThreadAbortException (or similar) to be thrown on the if, before the try block is entered?