Force Single Instance with Mutex handling restart application

Error processing SSI file

Answers

  1. Hall

    • 2020/5/13

    Single instance apps are well supported by the framework. It supports goodies such as disabling it on-the-fly, what you need here, and getting a notification when another instance is started. You'll want to use that to give your first instance the focus. Rewrite your Program.cs code like this:

    using System;
    using System.Windows.Forms;
    using Microsoft.VisualBasic.ApplicationServices;   // NOTE: add reference to Microsoft.VisualBasic
    
    namespace WindowsFormsApplication1 {
        class Program : WindowsFormsApplicationBase {
            public Program() {
                EnableVisualStyles = true;
                MainForm = new Form1();
                IsSingleInstance = true;
            }
            public static void Main(string[] args) {
                Instance = new Program();
                Instance.Run(args);
            }
            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
                // Nicety, focus the single instance.
                Instance.MainForm.Activate();
            }
            public static void Restart() {
                // What you asked for.  Use Program.Restart() in your code
                Instance.IsSingleInstance = false;
                Application.Restart();
            }
            private static Program Instance;
        }
    }
    
  2. Lucian

    • 2020/5/29

    Single instance apps are well supported by the framework. It supports goodies such as disabling it on-the-fly, what you need here, 

  3. Hoxha

    • 2016/1/8

    Worked well in combination with Application.Restart (). private const string ApplicationMutexName = "<myprogramkey>"; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main () { RunApplicationPreservingSingleInstance (); } private static void RunApplicationPreservingSingleInstance () { Mutex mutex = AcquireMutex (); if (mutex == null) { return; } try { RunApplication (); } finally { mutex.ReleaseMutex (); } }

  4. Brown

    • 2021/4/30

    Single instance apps are well supported by the framework. It supports goodies such as disabling it on-the-fly, what you need here, and getting a 

  5. Palumbo

    • 2017/12/25

    I do:

        bool onlyInstance = false;
            mutex = new System.Threading.Mutex(true, "qFluid", out onlyInstance);
            int cntrSec = 0;
            //per far funzionare restart ,aspetto per 3 sec per vedere se va via servizio 
            while (!onlyInstance & cntrSec < 3)
            {
                System.Threading.Thread.Sleep(1000);
                cntrSec += 1;
            }
    
            if (!onlyInstance)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("The application is already arunning");
                App.Current.Shutdown();
            }
    
  6. Joziah

    • 2017/5/28

    Step 1: Add the System.Runtime.Remoting reference to your project. Step 2: Add this single instance class to your project. Step 3: Implement the ISingleInstanceApp interface in your main application class in App.xaml.cs (this interface is provided by the SingleInstance.cs file). For example:

  7. David

    • 2020/7/10

    This will in turn force other threads to wait until the Mutex is released by the owner thread. When you initialize a Mutex, you can assign it a 

  8. Lefebvre

    • 2017/12/2

    Application.Run (New Form1 ()) End Sub. End Class. Step 2: We will change the code shown above to use Mutex and restrict the access to the form creation to a single thread. This will in turn force other threads to wait until the Mutex is released by the owner thread.

  9. Braylen

    • 2019/9/28

    I'm not sure what exactly goes wrong in your case but some issues might be:

    • You should probably use try finally to close the mutex to maximize changes of proper cleanup
    • In case cleanup failed previous time then Mutex.WaitOne will throw an AbandonedMutexException instead of return true. In this case your code will exit with an error box while you can just continue.
    • You are giving the Mutex 5 seconds to get aquired. If your shutdown will take over 5 seconds then the next startup will fail. A better option might be to release mutex right before initiating shutdown. (Provided of course that the Mutex is there only for user convenience).

    example

    the following example will require that you use Program.Restart to restart the application. Else the time window can still be the problem.

    static class Program
    {
        private static Mutex _mutex;
    
        [STAThread]
        static void Main()
        {
            _mutex = new Mutex(false, "myprogramkey");
            try
            {
                try
                {
                    if (!_mutex.WaitOne(1))
                    {
                        _mutex.Dispose();
                        _mutex = null;
                        MessageBox.Show("Error!");
                        return;
                    }
                }
                catch (AbandonedMutexException) { /* Mutex wasn't property released last time.*/ }
    
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            finally
            {
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                    _mutex.Dispose();
                }
            }
        }
    
        public static void Restart()
        {
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
                _mutex = null;
                Application.Restart();
            }
        }
    }
    
  10. D'Angelo

    • 2018/3/2

    My attached sample code shows how to do so. Side note #2: Mutex scope. To prevent multiple instances across sessions on the same machine, 

  11. Sala

    • 2017/1/20

    Mutex object provides exclusive access to shared resources and synchronize threads in different processes. Also it ensures blocks of code are executed only once at a time. Most common requirement from client is creating single instance application that will block the user from launching more than one instance of a program at a time.

  12. Khalil

    • 2018/11/26

    What, Why and How with Mutex object. Mutex is nothing but mutual exclusion. It is quick way to ensure that only one instance of your program 

  13. Zakai

    • 2017/11/22

    Try using try..finally for managing the Mutex.I usually use this approach. Worked well in combination with Application.Restart().

        private const string ApplicationMutexName = "<myprogramkey>";
    
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            RunApplicationPreservingSingleInstance();
        }
    
        private static void RunApplicationPreservingSingleInstance()
        {
            Mutex mutex = AcquireMutex();
            if (mutex == null)
            {
                return;
            }
    
            try
            {
                RunApplication();
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    
        private static Mutex AcquireMutex()
        {
            Mutex appGlobalMutex = new Mutex(false, ApplicationMutexName);
            if (!appGlobalMutex.WaitOne(3000))
            {
                return null;
            }
            return appGlobalMutex;
        }
    
        private static void RunApplication()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    
  14. Berisha

    • 2017/10/14

    return TRUE; } void CMyApp::Restart() { m_bRestartAppOnExit = true; PostQuitMessage(ERROR_SUCCESS_RESTART_REQUIRED); } int CMyApp::ExitInstance() { if (m_hMutex) { ::ReleaseMutex(m_hMutex); CloseHandle(m_hMutex); m_hMutex = NULL; } if (m_bRestartAppOnExit) { TCHAR szFileName[MAX_PATH]; szFileName[0] = 0; DWORD dwSize = MAX_PATH; GetModuleFileName(0, szFileName, dwSize); HINSTANCE hInst = ShellExecute(0, _T("open"), // Operation to perform szFileName, // Application name _T(""), // Additional

  15. Nova

    • 2016/3/23

    Releases the Mutex once. The current instance has already been disposed. Start(); } // The main thread exits, but the application continues to 

  16. Avery

    • 2020/11/28

    There are essentially two instances in which an application can be run: Single Instance and Multiple Instances. Single Instance Applications. Single Instance Applications means that only one instance can be run at any given point in time. In other words, this means that you cannot run the same application simultaneously. Multiple Instance

  17. Luis

    • 2018/3/27

    I want only one instance of the application should run at a time. Length > 0) { bool instanceCountOne = false; using (Mutex mtex = new 

  18. Dennis

    • 2019/1/12

    criti reset, Precondition: Precondition: pc = leave-try pc = reset Effect: This will be a somewhat brute-force operational proof, that is, one that 

  19. Boone

    • 2018/5/22

    A circuit realization requires a procedure to force all handshake channels in [6] to avoid a global reset, and two forms of initialization play a role.

  20. Maximiliano

    • 2019/10/17

    ASP VB Functions ASP VB Keywords ASP Response ASP Request ASP Application ASP Typically you check for this to make sure you have one instance running.

Comments are closed.

More Posts