且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用互斥锁的应用程序的运行单个实例

更新时间:2023-11-22 17:05:34

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

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