单实例应用程序无法启动

问题描述 投票:0回答:1

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

    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);
    }

我在网上搜索了一个解决方案或另一种方法来创建单个实例应用程序但没有成功。

c# .net winforms mutex
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.