互斥量在 C# 中发布时不工作,但调试工作正常

mutex is not working when it release in C# but debug is working

我希望程序在 运行 已经 运行 时不再 运行。

代码在我使用调试模式时有效,但在它发布时无法使用。

代码如下

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        string mtxName = "test mutex";
        Mutex mtx = new Mutex(true, mtxName);
        TimeSpan tsWait = new TimeSpan(0, 0, 1);
        bool success = mtx.WaitOne(tsWait);
        if (!success)
        {
            MessageBox.Show("is running.");
            return;
        }

        Application.Run(new Form1());

我认为您可能没有将 Mutex 用于其预期目的,互斥锁用于控制对资源的访问以创建它们 'thread safe',也许您应该查看进程列表。

Process myProcess = Process.GetCurrentProcess();
var processExists = Process.GetProcesses().Any(
    p => p.ProcessName.Equals(myProcess.ProcessName) 
    && p.Id != myProcess.Id);
if (processExists)
    return;

但是如果你真的想使用互斥锁,试试

    static Mutex mutex = new Mutex(true, "Something unique here");

    [STAThread]
    static void Main()
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
        else
        {
            MessageBox.Show("is running.");
        }
    }

为什么不使用互斥量?

namespace My.Program
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            bool exclusive;
            System.Threading.Mutex appMutex = new System.Threading.Mutex(true, "My.Program", out exclusive);
            if (!exclusive)
            {
                MessageBox.Show("Another instance of My Program is already running.","My Program",MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
                return;
            }
            Application.SetCompatibleTextRenderingDefault(false);
            GC.KeepAlive(appMutex);
            Application.Run(new frmMyMainForm());
        }
    }
}