C# mutex issue to prevent second instance

天大地大妈咪最大 提交于 2019-12-12 05:57:46

问题


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;
 }


来源:https://stackoverflow.com/questions/6427741/c-sharp-mutex-issue-to-prevent-second-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!