使用waitone()方法

时间:2009-05-02 15:18:19

标签: c#

static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");

static void Main()
{
    // Wait a few seconds if contended, in case another instance
    // of the program is still in the process of shutting down.

    if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))
    {
      Console.WriteLine ("Another instance of the app is running. Bye!");
      return;
    }

    try
    {
      Console.WriteLine ("Running. Press Enter to exit");
      Console.ReadLine();
    }
    finally { mutex.ReleaseMutex(); }
}

http://www.albahari.com/nutshell/ch20.aspx

在此代码中:

if(mutex.WaitOne(TimeSpan.Zero, true)) 
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
    mutex.ReleaseMutex();
} 
else 
{
    MessageBox.Show("only one instance at a time");
}

http://sanity-free.org/143/csharp_dotnet_single_instance_application.html

没有if / bool的反转。

如果waitone()为true,那是否意味着实例已在运行?如果返回true,则当前线程将被阻塞,这意味着调用同一个应用程序的两个进程都将停止?

我的理解如下:

// Don't block the thread while executing code. 
//Let the code finish and then signal for another process to enter

没有意义是什么! (返回true),反之亦然。或换句话说,无论哪种方式都会发生什么?

我知道waitAll例如,等待所有线程完成。 Jon Skeet在他的网站上展示了一个很好的例子,这一点在我的脑海中浮现(归功于他的解释)。很明显waitOne等待一个线程完成。返回值让我感到困惑。

2 个答案:

答案 0 :(得分:19)

等待互斥锁意味着等到你可以获得它。

如果可以在给定时间内获取互斥锁,则互斥锁上的WaitOne将返回true。如果不能,则该方法将返回false。如果获得了互斥锁,那么当您完成互斥锁时,您有责任释放该互斥锁。

如果您可以获得一个命名的互斥锁,那么目前没有其他人拥有它。

所以,回顾一下。如果您可以获取互斥锁,则该方法将返回true,并且就您的问题而言,您是应用程序的第一个/唯一实例。

如果您无法获取互斥锁,则该方法返回false,并且当前还有另一个应用程序实例拥有该名称的互斥锁。

答案 1 :(得分:1)

在MSDN中,mutex.WaitOne()的描述如下:

  

阻止当前线程直到   当前WaitHandle收到一个信号。

返回值为:如果当前实例收到信号,则为true

因此,在应用程序启动一次之前,它不会从mute.WaitOne()方法接收任何信号。线程被阻塞,如说明中所述。

所以回答你的问题:

  

没有意义是什么! (返回true),反之亦然。

如果你否定了mutex.WaitOne()方法,那么你将检查:如果不是waitOne(),则意味着你检查waitOne是否没有用 true 响应。

我希望现在更清楚了。