简体   繁体   English

使用c#Mutex类的这种替代方式是否有任何损失?

[英]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.

相关问题 在C#中使用类接口时,有什么方法可以缩短语法? - Any way to shorten syntax when using class interface in C#? .NET核心是否支持SqlFileStream或使用C#从SQL Server中获取文件流的任何其他方法? - .NET core support for SqlFileStream or any alternative way to get a filestream out of SQL Server using C#? 在C#中有什么替代Constant吗? - Is there any alternative to Constant in C#? 有没有比FileStream.WriteByte()方法更快的替代方法,或者有什么方法可以在C#中加快FileStream.WriteByte()的速度? - Is there any faster alternative to FileStream.WriteByte() method or any way to speed up the FileStream.WriteByte() in C#? .NET C# 中的 FileSystemWatcher 有什么替代方案吗? - Is there any alternative for FileSystemWatcher in .NET C#? C# NUnit 中是否有任何替代方案可用于 AssemblyTearDown - is there any alternative in C# NUnit for AssemblyTearDown c#中互斥锁的使用 - Usage of Mutex in c# C# 互斥量处理 - C# Mutex handling 有没有办法访问C#中任何类的实例变量的地址? - Is there a way to access the address of instance variable of any class in C#? 有没有办法在 C# 的部分类中写入相同的属性名称? - Is there any way to Write same property name in partial class in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM