I have created the following test program:
static void Main(string[] args)
{
using (var mutex = new Mutex(false, "foobar"))
{
Console.WriteLine("Created mutex");
try
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
{
Console.WriteLine("Unable to acquire mutex");
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
Console.WriteLine("Mutex was abandoned");
}
Console.WriteLine("Acquired mutex - sleeping 10 seconds");
Thread.Sleep(10000);
}
finally
{
mutex.ReleaseMutex();
Console.WriteLine("Released mutex");
}
}
The idea is that I run the program, and while the thread is sleeping for 10 seconds, I kill the process via task manager. Next time I run the process, I'm expecting that the AbandonedMutexException
would be caught on the WaitOne()
call. But I'm not seeing the output "Mutex was abandoned".
The MSDN documentation mentions the following:
When a thread abandons a mutex, the exception is thrown in the next thread that acquires the mutex.
However, it looks like the OS is releasing the mutex when my process is killed (rather than another thread within the same application).
Is there a way for me to be able to detect a mutex abandoned in this manner?