互斥结果在系统中是不同的

时间:2013-01-16 09:50:17

标签: c# .net multithreading mutex

我在C#中有一个控制台应用程序,我想限制我的应用程序一次只运行一个实例。它在一个系统中工作正常。当我尝试在另一个系统中运行exe时,它不起作用。问题是在一台电脑中我只能打开一个exe。当我尝试在另一台PC上运行时,我可以打开多个exe.How我可以解决这个问题吗?以下是我写的代码。

string mutexId = Application.ProductName;
using (var mutex = new Mutex(false, mutexId))
{
    if (!mutex.WaitOne(0, false))
    {
        MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        return;
    }

        //Remaining Code here
}

2 个答案:

答案 0 :(得分:1)

无论如何我会用这种方法:

// Use a named EventWaitHandle to determine if the application is already running.

bool eventWasCreatedByThisInstance;

using (new EventWaitHandle(false, EventResetMode.ManualReset, Application.ProductName, out eventWasCreatedByThisInstance))
{
    if (eventWasCreatedByThisInstance)
    {
        runTheProgram();
        return;
    }
    else // This instance didn't create the event, therefore another instance must be running.
    {
        return; // Display warning message here if you need it.
    }
}

答案 1 :(得分:0)

我很好的旧解决方案:

    private static bool IsAlreadyRunning()
    {
        string strLoc = Assembly.GetExecutingAssembly().Location;
        FileSystemInfo fileInfo = new FileInfo(strLoc);
        string sExeName = fileInfo.Name;
        bool bCreatedNew;

        Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
        if (bCreatedNew)
            mutex.ReleaseMutex();

        return !bCreatedNew;
    }

Source