WPF Single Instance Best Practices

前端 未结 11 1532
名媛妹妹
名媛妹妹 2020-12-07 08:19

This is the code I implemented so far to create a single instance WPF application:

#region Using Directives
using System;
using System.Globalization;
using S         


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 09:14

    My Solution for a .Net Core 3 Wpf Single Instance Application:

    [STAThread]
    public static void Main()
    {
        StartSingleInstanceApplication();
    }
    
    public static void StartSingleInstanceApplication()
        where T : RichApplication
    {
        DebuggerOutput.GetInstance();
    
        Assembly assembly = typeof(T).Assembly;
        string mutexName = $"SingleInstanceApplication/{assembly.GetName().Name}/{assembly.GetType().GUID}";
    
        Mutex mutex = new Mutex(true, mutexName, out bool mutexCreated);
    
        if (!mutexCreated)
        {
            mutex = null;
    
            var client = new NamedPipeClientStream(mutexName);
            client.Connect();
    
            using (StreamWriter writer = new StreamWriter(client))
                writer.Write(string.Join("\t", Environment.GetCommandLineArgs()));
    
            return;
        }
        else
        {
            T application = Activator.CreateInstance();
    
            application.Exit += (object sender, ExitEventArgs e) =>
            {
                mutex.ReleaseMutex();
                mutex.Close();
                mutex = null;
            };
    
            Task.Factory.StartNew(() =>
            {
                while (mutex != null)
                {
                    using (var server = new NamedPipeServerStream(mutexName))
                    {
                        server.WaitForConnection();
    
                        using (StreamReader reader = new StreamReader(server))
                        {
                            string[] args = reader.ReadToEnd().Split("\t", StringSplitOptions.RemoveEmptyEntries).ToArray();
                            UIDispatcher.GetInstance().Invoke(() => application.ExecuteCommandLineArgs(args));
                        }
                    }
                }
            }, TaskCreationOptions.LongRunning);
    
            typeof(T).GetMethod("InitializeComponent").Invoke(application, new object[] { });
            application.Run();
        }
    }
    

提交回复
热议问题