Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Mutex c# Safe handle has been closed

Here is my code to make a method call mutually exlcussive

public class X
{
    private static Mutex mutex = new Mutex(true, "MutexForFile");
    public IList<string> DoIt(IList<string> documents)
    {
        var result = new List<string>();
        if (mutex.WaitOne())
        {
            using (var agent = new MyClass())
            {
                // operation login
                if (agent.LibraryLogon("**", "***"))
                {
                    try
                    {
                        //codes to access shared resource
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat("");
                    }
                    finally
                    {
                        if (!mutex.SafeWaitHandle.IsClosed)
                        {
                            mutex.ReleaseMutex();
                        }
                        mutex.Dispose();
                    }
                    Log.DebugFormat("Completed");

                }
                else
                {
                    throw new Exception("Unable to Login Session");
                }
            }
            Log.DebugFormat("Completed Do it");
        }
        return result;
    }
}

I am forced to do the check if (!mutex.SafeWaitHandle.IsClosed) as I got ObjectDisposedException saying "Safe handle has been closed" when I call mutex.ReleaseMutex().

Is it the right way to avoid this exception?

Do any once can suggest any pitfals or issues with this codes?

Upvotes: 1

Views: 3261

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

You should avoid disposing the mutex while another thread is waiting for it:

Thread #1: WaitOne() -> gets ownership
Thread #2: WaitOne() -> waits for thread #1
Thread #1: ReleaseMutex() -> causes thread #2 to continue
Thread #1: Dispose()
Thread #2: ReleaseMutex() -> mutex was disposed by thread #1

The SafeWaitHandle.IsClosed just prevents the exception from appearing, but does not solve the underlying issue. It can only be solved in the code which spawns these threads, not within the thread - and perhaps you should not have multiple threads attempting to log in simultaneously?

Upvotes: 4

Related Questions