Wait Completed Due to abandoned mutex

611 views Asked by At

While running the first instance of the below app it prints "Acquired". However if i start the second one it waits for 1 min. During that interval if press enter and leave the "first instance" it throws "Wait Completed Due to abandoned mutex" exception in second instance. Is it not suppose to acquire the thread?! (As the first instance released it already?!)

   using (var m1 = new Mutex(false, "consoleapp"))
        {

            if (!m1.WaitOne(60000, false))
            {
                Console.WriteLine("It is already runnig");

            }
            else
            {
                Console.WriteLine("Acquired");
                Console.ReadLine();
            }

        }
1

There are 1 answers

0
Kalyani Ramamurthy On BEST ANSWER

You should explicitly release ownership of the mutex by calling m1.Release() in the else block. Otherwise it gets disposed but not released, hence the exception thrown by WaitOne() [in Comments by Hristo]