仅允许一个实例-但退出第一个 [英] Allow only one instance - but exit the first

查看:94
本文介绍了仅允许一个实例-但退出第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我只允许我的应用程序的一个实例.因此,使用Mutex似乎是实现这一目标的好机会.但是我发现的所有示例都描述了如何关闭辅助启动的实例.

如果第二个实例开始使用(System.Threading.)Mutex,是否有方法向第一个实例发出信号?还是有另一个干净的方法可以在第二个实例启动时关闭我的应用程序的第一个实例?

谢谢!! :)

Gobble-G

Hi,

I want to allow only one instance of my application. So using Mutex seems to be a good possibility to achieve that. But all examples I found describe how to close the instance that was started secondary.

Is there a way to signal the first instance if a second instance starts using (System.Threading.)Mutex? Or is there another clean way to close the first instance of my application if a second instance starts?

Thanks!! :)

Gobble-G

推荐答案

您可以使用ManualResetEvent代替Mutex,并让第一个实例注册线程池等待它.当另一个实例启动时,它可以尝试打开MRE(如果存在),然后可以对其进行设置,这将通知第一个实例关闭,然后重置它,然后注册它的线程池,等待它.

像这样的东西:
Instead of a Mutex you could use a ManualResetEvent and have the first instance register a thread pool wait on it. When another instance starts it can attempt to open up the MRE, if it exists then it can set it which will signal the first instance to close and then reset it and then register it''s thread pool wait on it.

Something like this:
// all of this happens on startup obviously
bool createdNew = false;
EventWaitHandle instanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "MyInstanceEvent", out createdNew);
if (!createdNew)
{
    instanceEvent.Set();
}

instanceEvent.Reset();
ThreadPool.RegisterWaitForSingleObject(instanceEvent, (state, timedOut) =>
{
    instanceEvent.Close();

    // where this is the Form class
    this.Close(); 
}, null, Timeout.Infinite, true);


是的,这很好用.

我唯一需要添加的是线程同步以关闭应用程序.当我使用WPF时,我替换了您的行:
Yeah, this works great.

The only thing I had to add is a thread synchronization to close the application. As I use WPF I replaced your line:
this.Close();


作者:


by:

this.Dispatcher.Invoke(new Action(() => { Application.Current.Shutdown(); }));



非常感谢你! :)



Thank you very much! :)


这篇关于仅允许一个实例-但退出第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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