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(); }
}
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
没有意义是什么!(返回true),反之亦然.或者换句话说,无论哪种方式都会发生什么?
我知道waitAll例如,等待所有线程完成.Jon Skeet在他的网站上展示了一个很好的例子,这一点在我的脑海中浮现(归功于他的解释).很明显waitOne等待一个线程完成.返回值让我感到困惑.
ang*_*son 19
等待互斥锁意味着等到你可以获得它.
true如果可以在给定时间内获取互斥锁,则互斥锁上的WaitOne将返回.如果不能,该方法将返回false.如果获得了互斥锁,那么当您完成互斥锁时,您有责任释放该互斥锁.
如果您可以获得一个命名的互斥锁,那么目前没有其他人拥有它.
所以,回顾一下.如果您可以获取互斥锁,则该方法将返回,true并且就您的问题而言,您是应用程序的第一个/唯一实例.
如果您无法获取互斥锁,则该方法返回,false并且当前还有另一个应用程序实例拥有该名称的互斥锁.