简体   繁体   English

强制应用程序 winform c# 的一个实例

[英]Enforce one instance of an application winform c#

Without using a global mutex lock in an application, is there any safe way to ensure only one instance of an application is running on a system?如果不在应用程序中使用全局互斥锁,是否有任何安全的方法来确保系统上只有一个应用程序实例正在运行? I have found out that bugs and errors that occur during an applications lifetime in memory can lead to many problems within a system, especially if pared with a global mutex lock.我发现在 memory 中的应用程序生命周期内发生的错误和错误可能会导致系统内出现许多问题,尤其是在与全局互斥锁相匹配的情况下。 Any suggestions would be much appreciated.任何建议将不胜感激。

Thanks for reading.谢谢阅读。

You can use Mutex to ensure a single instance app.您可以使用Mutex来确保单个实例应用程序。 Put the following code in the Main function of your WinForms app:将以下代码放入WinForms应用程序的 Main function 中:

static class Program
{
    static Mutex mutex = new Mutex(true, "<some_guid_or_unique_name>");

    [STAThread]
    static void Main()
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
           // do the app code
           Application.Run();

           // release mutex after the form is closed.
           mutex.ReleaseMutex();
           mutex.Dispose();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM