微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mutex 不会同时停止两个程序实例的运行

如何解决Mutex 不会同时停止两个程序实例的运行

我正在尝试使用互斥锁来一次只允许运行一个程序实例。我从我正在编写的另一个程序中重用了互斥锁代码,结果发现它并没有阻止我的程序的两个实例同时运行。但是,我的互斥体代码在我的其他程序中有效。下面是Program.cs的完整代码(打开文件代码无关)。你能帮我解决这个问题吗?谢谢!

注意:我的原始代码基于此 SO 答案:https://stackoverflow.com/a/819808/12946280

using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NTCSAttendanceKiosk
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Make a mutex and detect if another instance of the program is running
            Mutex mutex = new Mutex(true,"AtteNTCSKioskMutex",out bool mutexResult);

            if (!mutexResult)
            {
                // Exit if it's already running
                return;
            }

            // Prevent the mutex from being released by the GC
            GC.KeepAlive(mutex);

            // Read the connection string from the file
            try
            {
                sqlConnectionInfo.ConnectionString = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\kiosk_config\\connection_string.txt");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("The file connection_string.txt does not exist. Please place the connection string in that file and place it in <your user folder>\\kiosk_config\\. The kiosk program will Now exit.","Connection String File Not Found",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            catch (IOException)
            {
                MessageBox.Show("File I/O error when loading connection_string.txt. The kiosk program will Now exit.","File I/O Error",MessageBoxIcon.Error);
                return;
            }

            // Read the kiosk location name from the file
            try
            {
                sqlConnectionInfo.KioskLocation = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\kiosk_config\\location.txt");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("The file location.txt does not exist. Please place the kiosk location name in that file and place it in <your user folder>\\kiosk_config\\. The kiosk program will Now exit.",MessageBoxIcon.Error);
                return;
            }
            catch (IOException)
            {
                MessageBox.Show("File I/O error when loading location.txt. The kiosk program will Now exit.",MessageBoxIcon.Error);
                return;
            }

            Application.Run(new KioskForm());
        }
    }
}

解决方法

您可以通过同时运行多个实例来测试以下代码。

static void Main(string[] args)
{
    using (var mutex = new Mutex(true,"UniqueSystemWideMutexName"))
    {
        //Timeout is set to zero so we don't block
        if (!mutex.WaitOne(0))
        {
            Console.WriteLine("Program already running");
            Console.ReadKey();
            return;
        }
        Console.WriteLine("This is the only program running");
        Console.ReadKey();
    }
}

如果您因任何原因无法使用 Disposeusing 块为我们所做的),请务必调用 ReleaseMutex

您也可以使用 OpenExisting 来检查互斥锁是否已经创建,但对于这个简单的用例来说不是必需的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?