WPF Single Instance Best Practices

前端 未结 11 1543
名媛妹妹
名媛妹妹 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:22

    The most straight forward way to handle that would be using a named semaphore. Try something like this...

    public partial class App : Application
    {
        Semaphore sema;
        bool shouldRelease = false;
    
        protected override void OnStartup(StartupEventArgs e)
        {
    
            bool result = Semaphore.TryOpenExisting("SingleInstanceWPFApp", out sema);
    
            if (result) // we have another instance running
            {
                App.Current.Shutdown();
            }
            else
            {
                try
                {
                    sema = new Semaphore(1, 1, "SingleInstanceWPFApp");
                }
                catch
                {
                    App.Current.Shutdown(); //
                }
            }
    
            if (!sema.WaitOne(0))
            {
                App.Current.Shutdown();
            }
            else
            {
                shouldRelease = true;
            }
    
    
            base.OnStartup(e);
        }
    
        protected override void OnExit(ExitEventArgs e)
        {
            if (sema != null && shouldRelease)
            {
                sema.Release();
            }
        }
    
    }
    

提交回复
热议问题