如何确保单个实例应用程序(在多个虚拟桌面上)?

时间:2019-04-12 03:27:44

标签: c# single-instance

我正在编写一个C#WinForms应用程序,我需要确保在任何给定时间都在运行一个实例。我以为我可以使用Mutex(https://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/)来工作。

当我使用单个台式机时,此方法工作正常。但是,当Windows 10中打开多个虚拟桌面时,这些桌面中的每一个都可以托管该应用程序的另一个实例。

是否可以在所有台式机上限制单个实例?

1 个答案:

答案 0 :(得分:4)

如果您查看Remarks section of the docs(请参见Note块),您会发现,您要做的就是在互斥量前加上"Global\"。这是WinForms的示例:

// file: Program.cs
[STAThread]
private static void Main()
{
    using (var applicationMutex = new Mutex(initiallyOwned: false, name: @"Global\MyGlobalMutex"))
    {
        try
        {
            // check for existing mutex
            if (!applicationMutex.WaitOne(0, exitContext: false))
            {
                MessageBox.Show("This application is already running!", "Already running",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        // catch abandoned mutex (previos process exit unexpectedly / crashed)
        catch (AbandonedMutexException exception) { /* TODO: Handle it! There was a disaster */ }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}