Sometimes we only need to allow one instance of the application to run. When the process starts, if an instance of the application is found to be running, it will automatically stop running. We usually use mutex in the main function. The general syntax is:
[STAThread]static void Main(){bool createNew;using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew)){if (createNew){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1());}else{MessageBox.Show("Only one instance of this application is allowed!");}}}
When looking for answers, we often come and go in a hurry, so we don't care about the features and precautions of mutex. After a simple test, OK and use it. At this point, we ignore an important prerequisite: mutex naming rules. The preceding statement runs under a single user. in multiple users, each user can start an instance, which means that the operation of a single instance cannot be guaranteed.
If you need to use it on the terminal server and only allow one instance, use the following method:
[STAThread]static void Main(){bool createNew;try{using (System.Threading.Mutex m = new System.Threading.Mutex(true, "Global\\" + Application.ProductName, out createNew)){if (createNew){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1());}else{MessageBox.Show("Only one instance of this application is allowed!");}}}catch{MessageBox.Show("Only one instance of this application is allowed!");}}