简体   繁体   English

防止多个Windows应用程序实例

[英]Prevent multiple windows application instances

I have an application which can be used in 2 different ways, depending on whether I pass an argument to the main or not. 我有一个应用程序,可以通过2种不同的方式使用它,具体取决于我是否将参数传递给main。 With the following sample code I can: 使用以下示例代码,我可以:

- Start multiple instances, each with unique arguments -启动多个实例,每个实例都有唯一的参数
- Start one instance without arguments -启动一个不带参数的实例

static void Main(string[] args)
{
     string mutexName = "";
     if (args.Length > 0)
     {
         mutexName = args[0];
     } else 
     {
         mutexName = "NoArgs";
     }

     using (Mutex appMutex = new Mutex(false, String.Format("{0}-{1}", mutexName, appGuid)))
     {
         if (!appMutex.WaitOne(0, false))
         {
             MessageBox.Show("Instance already running");
             return;
         }

         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1());
     }
 }

Works perfectly! 完美的作品! But I would also want applications with arguments and no arguments be mutually exluded. 但是我也希望带有参数且没有参数的应用程序相互排斥。 As in.. If one or more applications with arguments are open, you cannot start one without arguments, and vice versa, if a program without args is open, you cannot start any program with args. 如图所示。如果打开了一个或多个带有参数的应用程序,则无法启动没有参数的程序,反之亦然,如果打开了不带参数的程序,则无法启动任何带参数的程序。

Does anybody have an idea of how I can accomplish this? 有人知道我该如何做到吗? I've tried different ways with the mutex and I'm starting to think that this cannot be done with Mutexes. 我已经尝试过使用互斥锁采用不同的方式,而且我开始认为使用互斥锁无法做到这一点。 Or I'll need "group" mutexes or something. 否则我将需要“组”互斥锁或其他东西。

You're saying that if a NoArgs application is launched, no other application can be launched. 您是说,如果启动了NoArgs应用程序,则无法启动其他应用程序。 So check this firsthand. 因此,请直接检查此内容。

Then: 然后:

  • If you're launching your application without args, you can start only if there is no application launched. 如果要启动不带args的应用程序,则只能在没有启动任何应用程序的情况下启动。
  • If you're launching your application with args, you can launch it if the application has not been launched with a mutex of the same name. 如果要使用args启动应用程序,则可以在未使用同名互斥锁启动应用程序的情况下启动它。

You can't determine with a mutex if there is a remaining application already launched. 您无法使用互斥锁确定是否已经启动了剩余的应用程序。 For this, you need a counting mutex , also called a semaphore . 为此,您需要一个计数互斥 ,也称为信号量 You may use a semaphore to determine the number of applications launched. 您可以使用信号量来确定启动的应用程序数量。 Then, you need a mutex for the "NoArgs" case, the mutex for each argument-passed mutex name, and a semaphore to count successfully launched applications. 然后,对于“ NoArgs”情况,您需要一个互斥锁,对于每个参数传递的互斥锁名称,都需要一个互斥锁,并需要一个信号灯来计数成功启动的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM