@ Mutex object (Mutex)
A mutex is similar to a monitor object.CodeAt the same time, only one thread is executing the block. The main difference between a mutex object and a monitor object is that the mutex object is generally used for cross-process thread synchronization, while the monitor object is used for intra-process thread synchronization. Two types of mutex objects are available: one is name mutex, and the other is anonymous mutex. In a cross-process, naming mutex is used. A named mutex is a system-level mutex, which can be used by other processes, you only need to specify the name to enable the mutex when creating a mutex. In. NetMutual Exclusion is throughMutexClass.
Mutex CTX = mutex. openexisting (name );
In fact,OpenexistingThe function has two overloaded versions:
Mutex. openexisting (string)
Mutex. openexisting (string, mutexrights)
For the default first function, the second function is actually implemented.Mutexrights. Synchronize | mutexrights. ModifyOperation.
Because the monitor is designed based on. NetFramework, andMutexClass is the system kernel object encapsulatedWin32To achieve mutex, And the mutex operation requires request interruption. Therefore, the performance of the monitor is better than that of the mutex object during intra-process thread synchronization.
Typical use of mutex SynchronizationThree steps are required: 1. Open or createMutexInstance; 2. CallWaitone ()Third, the final callReleasemutexTo release the mutex.
1 Static Public Void Addstring ( String Str)
2 {
3 // Set the timeout period and exit the non-default hosting context before wait
4 If (_ Maid. waitone ( 1000 , True ))
5 {
6_ Resource. Add (STR );
7_ CTX. releasemutex ();
8}
9 }
10
Note thatWaitone ()AndReleasemutex ()It must appear in pairs. Otherwise, the process will be deadlocked (. Net2.0) The framework will throwAbandonedmutexexceptionException.
Remaining Content