Mutex: A Mutex object.
Mutex range: Mutex within a multi-process range can also be used for synchronization of multiple threads in the same process. If the application scenario is the Mutex of the same process class, Mutex is unnecessary, using Lock or Monitor should be a good choice. Because the acquisition and generation of Mutex is no more than an order of magnitude slower than Lock or Monitor.
Local Mutex: if the name parameter is not passed when constructing a Mutex object, the local Mutex is constructed. The local Mutex is used for multi-thread synchronization in the same process.
System Mutex: To construct a Mutex, the name must be passed. The system Mutex is used for synchronization in multiple processes.
The Code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; namespace ThreadPrint {/// <summary> /// Mutex: exclusive range: Cross-process. /// Test 1: first run ThreadPrint to generate thread 1, // then run ThreadPrint again to generate thread 2. After thread 1 calls ReleaseMutex () to release, thread 2 will immediately execute // Test 2: first run ThreadPrint to generate process 1, // then run ThreadPrint again to generate process 2, and then close process 1, process 2 will cause AbandonedMutexException // </summary> class MutexTest {public static void Test () {// The named mutex uniquely identifies using on the terminal (var Mutex = new mutex (false, "Hbb0b0 ")) {try {// WaitOne checks whether other processes occupy the mutex. // If Mutex is occupied by other processes, the current process waits for 30 seconds. If Mutex is not released before the termination of other processes within 30 seconds, the current thread will immediately receive an AbandonedMutexException. // Mutex. waitOne (TimeSpan. fromSeconds (30), false) // If Mutex is occupied by other processes, the current process waits for 30 seconds. If Mutex is released by other processes within 30 seconds, // then the current thread immediately unblocks and continues execution. If (! Mutex. WaitOne (TimeSpan. FromSeconds (30) {Console. WriteLine ("Another app instance is running. Bye! "); Return ;}// other processes have released the mutex catch (AbandonedMutexException e) {Console. writeLine (e. message);} RunProgram (); Thread. sleep (10000); mutex. releaseMutex (); Console. writeLine ("mutex. releaseMutex () ") ;}} static void RunProgram () {Console. writeLine ("Running. press Enter to exit ");}}}