C# prevent multiple instance of console application running

Sudip Bhatt 2,276 Reputation points
2021-01-06T19:13:26.393+00:00

I got a code which prevent multiple instance of console application running. help me to understand the below code'

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

      Application.Run(new Form1());
   }
}

private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";

1) why they use GUID here ? what is the meaning of "Global\" + appGuid) ?

2) they pass false new Mutex(false) what is the meaning of false or true here ?

3) what is the meaning of this line if(!mutex.WaitOne(0, false)) ?
4) what WaitOne() does ?

5) why they pass 0 and false in WaitOne ?

please answer for my 5 points for guidance.

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
0 comments No comments
{count} vote

Accepted answer
  1. Timon Yang-MSFT 9,591 Reputation points
    2021-01-08T07:07:15.647+00:00

    Regarding question 1, Castorix31 said very clearly, regarding question 2, the document also described clearly:

    If name is not null and initiallyOwned is true, the calling thread owns the mutex only if the named system mutex was created as a result of this call. Since there is no mechanism for determining whether the named system mutex was created, it is better to specify false for initiallyOwned when calling this constructor overload. You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership.

    The following questions are all about WaitOne.
    The first parameter 0 indicates the time you want to wait.
    Suppose you want to use a phone booth on the street. When you see someone in the phone booth is using it, will you leave immediately or wait for that person to complete the call?
    0 means leave immediately, set to a certain value (milliseconds) means the time you waited, if the person is not over at that time, you will not continue to wait but leave.
    You can also set it to -1, which means to wait indefinitely.
    As for the second parameter exitContext, I tried to describe it in my own words, but found that my description will not be clearer than the explanation in this link:
    WaitOne exitContext


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,436 Reputation points
    2021-01-06T20:43:59.477+00:00

    Hello @Sudip Bhatt

    This was written in VS2019, C#9 and test in this application.

    using System;  
    using System.Diagnostics;  
    using System.Runtime.InteropServices;  
    using System.Windows.Forms;  
    using System.Threading;  
      
      
    namespace Async_Enumerables  
    {  
      
        static class Program  
        {  
            [DllImport("user32.dll")]  
            static extern bool SetForegroundWindow(IntPtr hWnd);  
              
            [STAThread]  
            static void Main()  
            {  
                Application.SetHighDpiMode(HighDpiMode.SystemAware);  
                  
                var needToCreateNew = true;  
                  
                using var mutex = new Mutex(true, ThisNamespace(), out needToCreateNew);  
                  
                if (needToCreateNew)  
                {  
                    Application.EnableVisualStyles();  
                    Application.SetCompatibleTextRenderingDefault(false);  
                      
                    Application.Run(new Form1());  
                }  
                else  
                {  
                    var current = Process.GetCurrentProcess();  
                      
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))  
                    {  
                        if (process.Id == current.Id) continue;  
                        SetForegroundWindow(process.MainWindowHandle);  
                        break;  
                    }  
                      
                }  
            }  
            public static string ThisNamespace()  
            {  
                var myType = typeof(Program);  
                return myType.Namespace;  
            }  
        }  
    }  
    
    2 people found this answer helpful.

  2. Castorix31 85,881 Reputation points
    2021-01-06T21:07:01.32+00:00

    The Guid is to ensure the Mutex name is unique ( "Global" is explained in the original C++ article)
    Other answers are in the MSDN doc :
    Mutex Constructors
    Remarks for WaitOne explanation

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.