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 enterno的含义是什么!(返回true),反之亦然。或者换句话说,无论哪种情况都会发生什么?
例如,我知道waitAll会等待所有线程完成。Jon Skeet在他的网站上展示了一个很好的例子,这一直留在我的脑海中(归功于他的解释)。所以很明显,waitOne会等待一个线程完成。返回值是让我困惑的地方。
发布于 2009-05-02 15:50:00
等待互斥意味着等待,直到你可以获得它。
如果可以在给定时间内获取互斥锁,则互斥锁上的WaitOne将返回true。如果不能,该方法将返回false。如果获得了互斥锁,则在使用完互斥锁后释放该互斥锁是您的责任。
如果你能获得一个命名互斥锁,那么目前没有其他人拥有它。
所以,让我们回顾一下。如果您可以获取互斥锁,那么该方法将返回true,并且您是您的应用程序的第一个/唯一的实例。
如果无法获取互斥锁,则该方法返回false,并且当前有另一个应用程序实例使用该名称拥有互斥锁。
发布于 2009-05-02 15:41:44
在MSDN中,mutex.WaitOne()的描述如下:
在当前WaitHandle收到信号之前,
会阻塞当前线程。
如果当前实例接收到信号,则返回值为: true
因此,在应用程序启动一次之前,它不会收到来自mute.WaitOne()方法的任何信号。正如描述中所说的,线程被阻塞了。
所以我来回答你的问题:
,no是什么意思!(返回true),反之亦然。
如果您否定了mutex.WaitOne()方法,那么您将检查:如果不是waitOne(),则意味着您检查waitOne是否没有返回true。
我希望这一点现在更清楚了。
https://stackoverflow.com/questions/815011
复制相似问题