Search code examples
c#multithreadingconcurrencymutex

Mutex - TryOpenExisting vs new one


I'm thinking about Mutexes and I need some clarification about them. Should I try to open existing Mutex or create new one (of course both with the same name). Example of code:

First attempt - try open existing one:

private void AttemptOne()
{
    Mutex myMutex;
    if (!Mutex.TryOpenExisting("Mutex Name", out myMutex))
        myMutex = new Mutex(false, "Mutex Name");
    try
    {
        myMutex.WaitOne(3000);
        // code
    }
    catch { }
    finally
    {
        myMutex.ReleaseMutex();
        // myMutex.Dispose(); - should I call that or it will be called automatically when returning from method?
    }
}

Second attempt - create new Mutex:

private void AttemptTwo()
{
    using (Mutex mutex = new Mutex(false, "Mutex Name"))
    {
        try
        {
            mutex.WaitOne(3000);
            // code
        }
        catch { }
        finally { myMutex.ReleaseMutex(); }
    }
}

I have some questions, which bother me:

  • which attempt to use?

    Let assume that I have a background process with created Mutex, and at the same time Main process tries to do some work, which should be blocked until backgorund process finishes. If background process created its own Mutex, should I try to open it?

    Or create new Mutex in Main thread with the same name?

    What is the difference between those attempts?

  • should I call Dispose() in first Attempt?

    Or just assume that Mutex will be disposed when method returns? Will it be disposed then?

  • I assume that in second attempt Mutex will be Disposed (as its IDisposable) when using() ends. Am I right?

Solution

  • If you're planning to create the mutex if it doesn't exist anyway, then just go ahead and use the second method. If you're going for a different behavior based on the existence of the mutex, then you should use TryOpenExisting to check if it exists.

    As for your other questions: Yes, you should call the Dispose or Close method on the mutex when you're done with it. In order to allow the operating system to destroy it once it's not in use.

    Yes, using would call the Mutex object Dispose method.