Search code examples
multithreadingmutexwaitone

Wait Completed Due to abandoned mutex


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();
            }

        }

Solution

  • 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]