This article is a mirror article of machine translation, please click here to jump to the original article.

View: 19013|Reply: 0

[Source] C# only allows the correct writing of one instance of the application to run

[Copy link]
Posted on 12/10/2016 2:35:34 PM | | |
C# programs only allow one instance to run the correct code
http://www.itsvse.com/thread-3391-1-1.html
(Source: Architect)


The code below is also wrong!! Correct code as above!!


Sometimes we need to allow only one instance of the application to run, and when the process starts, if it finds that an instance of the application is running, it will automatically stop running. We usually implement it in the Main function via a Mutex mutex, which is usually written:

When we look for answers, we often come and go in a hurry, ignoring the features and precautions of Mutex. After a simple test, OK, take it and use it. At this point, we overlook an important prerequisite:Mutex naming conventions. The above writing method works without any problems under a single user; Under multi-user, each user can start one instance, so a single instance cannot be guaranteed.

If you need to use it on a terminal server and only allow one instance, use the following method:


Here is the description of MSDN:


On servers running terminal services, named system mutex can have two levels of visibility. If the name starts with the prefix "Global\", the mutex is visible in all terminal server sessions. If the name starts with the prefix "Local\", the mutex is only visible in the terminal server session that created it. In this case, each other terminal server session on the server can have a separate mutex with the same name. If you create a named mutex without specifying a prefix, it will take the prefix "Local\". In a terminal server session, two mutexes with different name prefixes are independent mutex, and the two mutex are visible to all processes in the terminal server session. That is, the prefix names "Global" and "Local" describe the range of the mutex name relative to the terminal server session, not to the process.






Previous:Registering components for COM interop is grayed out
Next:C# programs only allow one instance to run the correct code
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com