You can use aobject to provide exclusive access to a resource. The Mutex class uses more system resources than the class, but it can be marshaled across application domain boundaries, it can be used with multiple waits, and it can be used to synchronize threads in different processes. For a comparison of managed synchronization mechanisms, see .
For code examples, see the reference documentation for theconstructors.
A thread calls themethod of a mutex to request ownership. The call blocks until the mutex is available, or until the optional timeout interval elapses. The state of a mutex is signaled if no thread owns it.
A thread releases a mutex by calling itsmethod. Mutexes have thread affinity; that is, the mutex can be released only by the thread that owns it. If a thread releases a mutex it does not own, an is thrown in the thread.
Because the Mutex class derives from, you can also call the static or methods of WaitHandle to request ownership of a Mutex in combination with other wait handles.
If a thread owns a Mutex, that thread can specify the same Mutex in repeated wait-request calls without blocking its execution; however, it must release the Mutex as many times to release ownership.
If a thread terminates without releasing a Mutex, the mutex is said to be abandoned. This is a serious programming error because the resource the mutex is protecting might be left in an inconsistent state. In the .NET Framework version 2.0, anis thrown in the next thread that acquires the mutex.
In the .NET Framework versions 1.0 and 1.1, an abandoned Mutex is set to the signaled state and the next waiting thread gets ownership. If no thread is waiting, the Mutex remains in a signaled state. No exception is thrown.
Local and System Mutexes
Mutexes are of two types: local mutexes and named system mutexes. If you create a Mutex object using a constructor that accepts a name, it is associated with an operating-system object of that name. Named system mutexes are visible throughout the operating system and can be used to synchronize the activities of processes. You can create multiple Mutex objects that represent the same named system mutex, and you can use themethod to open an existing named system mutex.
A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the local Mutex object. Each Mutex object is a separate local mutex.
Access Control Security for System Mutexes
The .NET Framework version 2.0 provides the ability to query and set Windows access control security for named system objects. Protecting system mutexes from the moment of creation is recommended because system objects are global and therefore can be locked by code other than your own.
For information on access control security for mutexes, see theand classes, the enumeration, the , , and OpenExisting methods of the Mutex class, and the constructor.