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! ");
}
}
The following is a description of MSDN:
On the server that runs the terminal service, the named system mutex can have two levels of visibility. If the name is prefixed with "Global \", mutex is visible in all Terminal Server sessions. If the name is prefixed with "Local \", mutex is only visible in the terminal server session where it is created. In this case, each other Terminal Server session on the server can have an independent mutex with the same name. If you do not specify a prefix when creating a named mutex, it uses the prefix "Local \". In a Terminal Server session, only two mutex with different name prefixes are independent mutex, which are visible to all processes in the terminal server session. That is, the prefix names "Global \" and "Local \" indicate the scope of the mutex name relative to the terminal server session rather than the process.
From JustRun1983