2013-01-16 31 views
0

我在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 
} 
+0

其他什么系统是不工作的,你可以更特定的JEMI – MethodMan

+0

你是否指另一个系统?另一台PC? –

+4

“它不工作”是*从来没有足够的细节。你应该*总是*解释你期望看到什么以及你实际看到的是什么。 –

回答

0

我反而反正用这个办法:

// 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. 
    } 
} 
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