The mysterious life of mutexes
Last night I was talking with Ron Grabowski (of log4net fame) and the subject of mutexes came up. Specifically, the subject of abandoned mutexes across threads, AppDomains, and Processes. I was pretty sure what the behavior should be, but we wrote a set of test cases for that, with... surprising results.
My expectation that after I get a hold on a mutex, I have to explicitly let it go. If I am killed or interrupted somehow, then I would expect the next person to acquire the mutex to get an AbandonedMutexException.
The first code sample does exactly that:
We haven't explicitly release the mutex, but we let the thread die, on acquire, you'll get the expected AME.
Now, let us try it with processes, shall we?
We start our process, which spawn a second process, which would acquire a lock on the mutex, and then fail fast, killing the process. The first process, on attempting to get the process, will die horribly, as expected.
But not so fast, because this bit of code doesn't throw anything, and pretend that everything is right.
I am not really sure why this is the case, I would expect Envirionment.FailFast and an external Process.Kill to have the same behavior.
It gets to be even stranger, because we see the exact same problem when we are dealing with AppDomains:
I am not willing to comment on what is going on, I have the feeling that I am missing something.
Nevertheless, this is surprising behavior.