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.
|