C # correct implementation of only one instance of the application is allowed

Source: Internet
Author: User

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!");}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.