Use mutex to run code sharing with a single instance of your application

  • 2020-05-30 20:58:18
  • OfStack

System.Threading.Mutex: a synchronous primitive that grants exclusive access to a Shared resource to only one thread.
Implementation principle: when the program starts, request a mutex, if you can get access to the specified mutex, continue to run the program, otherwise exit the program.
Test code:


class Test
     {
         /// <summary>
         ///  The application's main entry point. 
         /// </summary>
          [STAThread]
         static void Main(string[] args)
         {
              bool flag=false;
              System.Threading.Mutex mutex=new System.Threading.Mutex(true,"Test",out flag);
              // The first 1 A parameter :true-- Gives the calling thread the initial ownership of the mutex 
              // The first 1 A parameter : The name of the mutex 
              // The first 3 A parameter : The return value , If the calling thread has been granted the original ownership of the mutex , It returns true
              if(flag)
              {
                   Console.Write("Running");
              }
              else
              {
                   Console.Write("Another is Running");
                   System.Threading.Thread.Sleep(5000);// Thread hanging 5 seconds 
                   Environment.Exit(1);// Exit the program 
              }
              Console.ReadLine();
         }

Operation results:
Run 1, output "Running".
Do not close the program run for the first time, run the second time, output "Another is Running", 5 seconds later, the program automatically exit.


Related articles: