【问题标题】:Mutex results are varying in systems互斥量结果在系统中有所不同
【发布时间】:2013-01-16 09:50:16
【问题描述】:

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

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
}

【问题讨论】:

  • 它在其他什么系统中不起作用,您能说得更具体一点吗?JEMI
  • 另一个系统是什么意思?另一台电脑?
  • “它不工作”是永远不够详细。你应该总是解释你期望看到什么和你实际看到什么。
  • 是的。它不能在另一台电脑上工作
  • 其他电脑有什么问题?

标签: c# .net multithreading mutex


【解决方案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.
    }
}

【讨论】:

    【解决方案2】:

    我的好旧解决方案:

        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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 2011-10-27
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多