/// <summary> ///A Boolean value that indicates whether the calling thread should have initial ownership of the mutex and whether the string is the name of the mutex and when the thread returns can indicate whether the calling thread has given initial ownership of the mutex initialized<see cref= "T:System.Threading.Mutex"/>a new instance of the class. /// </summary> /// <param name= "initiallyowned" >If True, the initial ownership of the system mutex named by the calling thread is given (if the named system mutex was created by this call), otherwise false. </param> ///<param name= "name" ><see cref= "T:System.Threading.Mutex"/>'s name. If the value is null, the<see cref= "T:System.Threading.Mutex"/>is not named. </param> ///<param name= "creatednew" >When this method returns, if a local mutex is created (that is, if<paramref name= "name"/>is null or an empty string) or a named system mutex that is specified, contains a Boolean value of true, or False if the specified naming system mutex already exists. This parameter is passed without initialization. </param> ///<exception cref= "T:System.UnauthorizedAccessException" >A named mutex exists and has access control security, but the user does not have<see cref= "F:system.security.accesscontrol.mutexrights.fullcontrol"/>. </exception> ///<exception cref= "T:System.IO.IOException" >a WIN32 error has occurred. </exception> ///<exception cref= "T:System.Threading.WaitHandleCannotBeOpenedException" >A named mutex could not be created because it might have the same name as another type of wait handle. </exception> ///<exception cref= "T:System.ArgumentException" ><paramref name= "name"/>more than 260 characters in length. </exception>[ securitycritical] [ReliabilityContract (Consistency.willnotcorruptstate, Cer.mayfail)] [__DynamicallyInvokab Le] PublicMutex (BOOLinitiallyowned,stringName out BOOLcreatednew): This(initiallyowned, Name, outCreatednew, (mutexsecurity)NULL) { }
Out return value, can create a mutex, returns true, cannot create mutex mutex, indicates that a running instance already exists, returns false.
BOOLIsapprunning =false; System.Threading.Mutex Mutex=NewSystem.Threading.Mutex (true, System.Diagnostics.Process.GetCurrentProcess (). ProcessName, outisapprunning);if(!isapprunning) {MessageBox.Show ("This program has been run"); Environment.exit (1);}Else{application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Application.Run (NewForm1 ());}
or//mutex Mutex class is the main feature of inter-process sharing, the process of mutual exclusion, grab locks, with the name of the logo. BOOLcreatednew; Mutex Mutex=NewMutex (false,"AAAA", outcreatednew);if(Mutex. WaitOne ( +,false ) ){ Try{Console.WriteLine ("start normally. " ) ; } finally{mutex.} ReleaseMutex (); }}Else{Console.WriteLine ("you have started a" ) ;}
Implementing single-instance programs with Mutext