AbandonedMutexException: The wait completed due to an abandoned mutex

13,561

Solution 1

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.

Solution 2

Where is the exception occurring? Does it happen when you do WriteMutex.WaitOne();?

If so, there must be something (presumably not in the code you posted) that takes ownership of it, then exits happening before you get the exception.

Using async methods could also be a problem with code using Mutexes due to swapping the threads around. Make sure you aren't using any of that stuff in a non-compatible way.

Also, be aware that named mutexts are not local to your application: other processes could be screwing with it (and the problem could be there). If you want something local, don't give it a name, or even better use something more efficient and less error prone like the lock keyword for such cases.

Some nice details about using Mutex properly (and avoiding issues like you seem to have) are here: What is a good pattern for using a Global Mutex in C#?

Solution 3

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

Share:
13,561

Related videos on Youtube

J. Doe
Author by

J. Doe

Updated on September 16, 2022

Comments

  • J. Doe
    J. Doe over 1 year

    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.