C# mutex issue to prevent second instance

2019-08-21 02:44发布

问题:

I got an interesting problem (C#/WPF application). I am using this code to prevent second instance of my application from running.

Mutex _mutex;
string mutexName = "Global\\{SOME_GUID}";
            try
            {
                _mutex = new Mutex(false, mutexName);
            }
            catch (Exception)
            {
//Possible second instance, do something here.
            }

            if (_mutex.WaitOne(0, false))
            {
                base.OnStartup(e);  
            }
            else
            {
            //Do something here to close the second instance
            }

If I put the code directly in the main exe under OnStartup method it works. However if I wrap the same code and put it in a separate assembly/dll and call the function from OnStartup method it doesn't detect second instance.

Any suggestions?

回答1:

What is _mutex variable life time, when it is placed to Dll? Maybe it is destroyed after OnStartup exits. Keep Single Instance wrapper class as your application class member, to have the same life time, as original _mutex variable.



回答2:

static bool IsFirstInstance()
{
    // First attempt to open existing mutex, using static method: Mutex.OpenExisting
    // It would fail and raise an exception, if mutex cannot be opened (since it didn't exist)
    // And we'd know this is FIRST instance of application, would thus return 'true'

    try
    {
        SingleInstanceMutex = Mutex.OpenExisting("SingleInstanceApp");
    }
    catch (WaitHandleCannotBeOpenedException)
    {
        // Success! This is the first instance
        // Initial owner doesn't really matter in this case...
       SingleInstanceMutex = new Mutex(false, "SingleInstanceApp");

        return true;
    }

    // No exception? That means mutex ALREADY existed!
    return false;
 }