C#互斥锁问题,以防止第二次实例 [英] C# mutex issue to prevent second instance

查看:402
本文介绍了C#互斥锁问题,以防止第二次实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个有趣的问题(C#/WPF应用程序).我正在使用此代码来防止应用程序的第二个实例运行.

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
            }

如果我将代码直接放在OnStartup方法下的主exe中,它将起作用.但是,如果我包装相同的代码并将其放在单独的程序集/dll中,然后从OnStartup方法调用该函数,则它不会检测到第二个实例.

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.

有什么建议吗?

推荐答案

_mutex变量的生命周期是什么,当它放置在Dll上时?可能在OnStartup退出后销毁了它.保留单实例包装器类作为您的应用程序类成员,以与原始_mutex变量具有相同的生存时间.

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.

这篇关于C#互斥锁问题,以防止第二次实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆