Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring only one application instance [duplicate]

Possible Duplicate:
What is the correct way to create a single instance application?

I have a Winforms app, which launches a splash screen via the following code:

Hide();
        bool done = false;
        // Below is a closure which will work with outer variables.
        ThreadPool.QueueUserWorkItem(x =>
                                  {
                                      using (var splashForm = new SplashScreen())
                                      {
                                          splashForm.Show();
                                          while (!done)
                                              Application.DoEvents();
                                          splashForm.Close();
                                      }
                                  });

        Thread.Sleep(3000);
        done = true;

The above is in the main form's codebehind and called from the load event handler.

However, how can I ensure that only one instance of the application will load at a time? In the load event handler of the main form, I could check if the process list is on the system (via GetProcessesByName(...)), but is there a better method?

Using .NET 3.5.

like image 213
GurdeepS Avatar asked Sep 07 '25 12:09

GurdeepS


1 Answers

GetProcessesByName is slow way of checking if another instance is running. The fastest and elegant method is using mutex:

[STAThread]
    static void Main()
    {
        bool result;
        var mutex = new System.Threading.Mutex(true, "UniqueAppId", out result);

        if (!result)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }

        Application.Run(new Form1());

        GC.KeepAlive(mutex);                // mutex shouldn't be released - important line
    }

Please also bear in mind that the code you presented is not the best approach. As it was advised in one of comments calling DoEvents() in a loop is not the best idea.

like image 139
michalczerwinski Avatar answered Sep 09 '25 07:09

michalczerwinski