0

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?

EM0
  • 5,369
  • 7
  • 51
  • 85
  • Take a look here: https://stackoverflow.com/questions/18002668/can-threadabortexception-skip-finally – Orace Jan 02 '19 at 16:22
  • In case of a call to the `Thread.Abort` (very bad practice) method in the middle of `myMutex.WaitOne()`, yes the mutex can be acquired and the boolean value not updated to true. And then the mutex is not released. The second piece of code looks safer. – Orace Jan 02 '19 at 16:34
  • I don' know why I bother asking detailed questions on SO any more when I know people will just scan them for a few key words looking to close it as a duplicate as fast as possible. This question is not about finally blocks at all. Nor is it specifically about ThreadAbortException, that was just an example. The question is: "Can a .NET thread be interrupted between a method returning and assigning its return value?" If it is answered by one of the two linked questions then what is the answer - yes or no? Alright, I'll ask it again *without* providing example code for context. – EM0 Jan 03 '19 at 09:27

0 Answers0