Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AbandonedMutexException: The wait completed due to an abandoned mutex

Tags:

c#

.net

.net-2.0

Why would the following structure cause an AbandonedMutexException. Even if there is an error or method returns. The mutex is being released.

static Mutex WriteMutex = new Mutex(false, @"Global\mutex2203");

public static void Demo()
{

    try
    {
        WriteMutex.WaitOne();

        //rest of coding stuff here
    }
    finally
    {
            WriteMutex.ReleaseMutex();
    }

}

Receives reports cant regenerate the bug.

Edit: The exception occurs at WriteMutex.WaitOne(); no other code. And only this method touches that mutex.

like image 401
J. Doe Avatar asked Dec 31 '15 02:12

J. Doe


2 Answers

An AbandonedMutexException is thrown when one thread acquires a Mutex object that another thread has abandoned by exiting without releasing it (see AbandonedMutexException). The code you cite in your question would not necessarily be the code that is causing the exception, only "receiving" it (i.e. detecting the situation that throws the exception).

That is, code in another thread (could be the same method but is likely not) acquires the Mutex but does not release it and permits its thread to exit without the Mutex ever being released. Then the thread running the code you show above throws the exception when it attempts to acquire the Mutex.

like image 91
Ken Clement Avatar answered Sep 18 '22 09:09

Ken Clement


You must also call WriteMutex.Dispose() in the finally block, but it is better to use a using block. Try to use this pattern: https://stackoverflow.com/a/229567/2185689

like image 40
Sergey Avatar answered Sep 21 '22 09:09

Sergey