【问题标题】:Single instance application not starting单实例应用程序未启动
【发布时间】:2018-05-29 13:20:29
【问题描述】:

我使用 .net 4.5 和 Main 类上的互斥锁开发了一个单实例 WinForm 应用程序。一些用户报告他们无法启动应用程序,因为互斥锁已被占用。

    static string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value + "-OrientalWave";
    public static string GUID { get { return guid; } }

    [STAThread]
    static void Main(string[] args)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

        // Single Instance Check
        bool createdNew;
        using (var mutex = new Mutex(true, guid, out createdNew))
        {
            if (createdNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                if (args.Length > 0)
                {
                    string filename = args[0];
                    Application.Run(new frmMain(filename));
                }
                else
                    Application.Run(new frmMain());
            }
            else
            {
                if (args.Length > 0)
                {
                    // If i want to open a file
                    string filename = args[0];

                    NamedPipesClient pipeClient = new NamedPipesClient();
                    pipeClient.Start();
                    pipeClient.SendMessage(filename);
                    pipeClient.Stop();
                }
                else
                    MessageBox.Show("Only single instance allowed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
    {
        try
        {
            var exception = (Exception)args.ExceptionObject;
            MessageBox.Show(exception.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Logger.Write(Logger.LogType.Error, exception.Source, "Message: " + exception.Message + " - Stack: " + exception.StackTrace);
        }
        catch { }
        Environment.Exit(0);
    }

我在网上搜索了创建单实例应用程序的解决方案或替代方法,但没有成功。

【问题讨论】:

  • 你把它作为你的应用程序的一个功能,所以并不奇怪。请避免重新发明这个轮子,它已经得到框架的支持。永远青睐那些被数十万程序员抨击、每天被测试数百万次的代码。 stackoverflow.com/a/29260770/17034
  • 在我看来,这段代码应该能按预期工作......

标签: c# .net winforms mutex


【解决方案1】:

如果有任何废弃的互斥锁,就会发生这种情况。您应该捕获 AbandonedMutexException 并通过调用 ReleaseMutex() 释放互斥锁; 那么你应该能够获得一个互斥体。

你可以在这里找到一个类似的用例http://gonetdotnet.blogspot.in/2017/08/solved-how-to-handle-log4net.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多