使用互斥锁的应用程序的运行单个实例 [英] Run single instance of an application using Mutex

查看:227
本文介绍了使用互斥锁的应用程序的运行单个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了只允许我使用互斥体的应用程序运行的单个实例。的code为如下。这是做正确的方式?有没有在code任何瑕疵?

如何当用户试图打开该应用程序的第二次显示已经运行的应用程序。在present(下code),我只是显示一个消息,另一个实例已在运行。

 静态无效的主要(字串[] args)
    {
        互斥_mut = NULL;        尝试
        {
            _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);
        }
        抓住
        {
             //写入处理程序
        }        如果(_mut == NULL)
        {
            _mut =新的Mutex(假,AppDomain.CurrentDomain.FriendlyName);
        }
        其他
        {
            _mut.Close();
            MessageBox.Show(实例已经运行);        }
    }


解决方案

我这样一次成功了,我希望它可以帮助:

 布尔createdNew;互斥M =新的Mutex(真的,对myApp,出createdNew);如果(!createdNew)
{
    //对myApp已经运行...
    MessageBox.Show(对myApp已经运行!,多个实例);
    返回;
}

In order to allow only a single instance of an application running I'm using mutex. The code is given below. Is this the right way to do it? Are there any flaws in the code?

How to show the already running application when user tries to open the application the second time. At present (in the code below), I'm just displaying a message that another instance is already running.

    static void Main(string[] args)
    {
        Mutex _mut = null;

        try
        {
            _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);
        }
        catch
        {
             //handler to be written
        }

        if (_mut == null)
        {
            _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName);
        }
        else
        {
            _mut.Close();
            MessageBox.Show("Instance already running");

        }            
    }

解决方案

I did it this way once, I hope it helps:

bool createdNew;

Mutex m = new Mutex(true, "myApp", out createdNew);

if (!createdNew)
{
    // myApp is already running...
    MessageBox.Show("myApp is already running!", "Multiple Instances");
    return;
}

这篇关于使用互斥锁的应用程序的运行单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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