Run one instance from the application

前端 未结 7 952
盖世英雄少女心
盖世英雄少女心 2020-12-16 06:49

I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the appl

7条回答
  •  爱一瞬间的悲伤
    2020-12-16 07:27

    I'd use a Mutex for this scenario. Alternatively, a Semaphore would also work (but a Mutex seems more apt).

    Here's my example (from a WPF application, but the same principles should apply to other project types):

    public partial class App : Application
    {
        const string AppId = "MY APP ID FOR THE MUTEX";
        static Mutex mutex = new Mutex(false, AppId);
        static bool mutexAccessed = false;
    
        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                if (mutex.WaitOne(0))
                    mutexAccessed = true;
            }
            catch (AbandonedMutexException)
            {
                //handle the rare case of an abandoned mutex
                //in the case of my app this isn't a problem, and I can just continue
                mutexAccessed = true;
            }
    
            if (mutexAccessed)
                base.OnStartup(e);
            else
                Shutdown();
        }
    
        protected override void OnExit(ExitEventArgs e)
        {
            if (mutexAccessed)
                mutex?.ReleaseMutex();
    
            mutex?.Dispose();
            mutex = null;
            base.OnExit(e);
        }
    }
    

提交回复
热议问题