[英]Are there any loss in this alternative way of using c# Mutex class?
I have an application (I didn't write this) that is using Mutex like this: 我有一个使用Mutex的应用程序(我没有写这个):
static void Main(string[] args)
{
Mutex mutex = null;
try
{
mutex = Mutex.OpenExisting("SINGLEINSTANCE");
if (mutex != null)
{
return;
}
}
catch (WaitHandleCannotBeOpenedException ex)
{
mutex = new Mutex(true, "SINGLEINSTANCE");
}
// critical section here
}
But I know that the correct way is this: 但是我知道正确的方法是这样的:
private readonly Mutex m = new Mutex("SINGLEINSTANCE");
static void Main(string[] args) {
m.WaitOne();
try {
/* critical code */
}
finally {
m.ReleaseMutex();
}
}
This is used because only one process of this application can run at the same time. 这样做是因为该应用程序只能同时运行一个进程。 It is a console application that do some asynchronous job for a web application. 它是一个控制台应用程序,为Web应用程序执行一些异步工作。
This code is in production, I don't wanna change it, unless there are some big problem with this code... Are there? 该代码正在生产中,我不想更改它,除非此代码有一些大问题...存在吗?
The old code has a race condition where two processes could try to start at the same time, the 2nd one to start will throw a exception and crash on the new Mutex(true, "SINGLEINSTANCE");
旧代码有一个竞争条件,其中两个进程可以尝试同时启动,第二个启动将引发异常并在new Mutex(true, "SINGLEINSTANCE");
上崩溃new Mutex(true, "SINGLEINSTANCE");
line. 线。 If the mutex already existed and you don't have the race condition the program will quit gracefully and never execute the critical section. 如果互斥体已经存在,并且您没有争用条件,则程序将正常退出,并且从不执行关键部分。
Your new code can't compile because you did not use a valid constructor for Mutex
, however if you had passed in false
your code would wait for the previous mutex to be released then it would continue on with the critical section, never exiting the program early. 您的新代码无法编译,因为您没有为Mutex
使用有效的构造函数,但是,如果您传入的是false
您的代码将等待先前的互斥锁被释放,然后它将继续执行关键部分,而不会退出程序早。
The "Correct" way would be to combine the two methods and try and create the mutex and see if you are the owner of it using the overload with the out
parameter. “正确”的方法是将两种方法结合起来,尝试创建互斥锁,并使用重载与out
参数来查看您是否是互斥锁的所有者。
static void Main(string[] args)
{
bool taken;
using(Mutex mutex = new Mutex(true, "SINGLEINSTANCE", out taken))
{
if(!taken)
return;
try
{
// critical section here
}
finally
{
mutex.ReleaseMutex();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.