Export (0) Print
Expand All

Mutex Class

A synchronization primitive that can also be used for interprocess synchronization.

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public sealed class Mutex : WaitHandle

The Mutex type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMutex()Initializes a new instance of the Mutex class with default properties.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMutex(Boolean)Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsMutex(Boolean, String)Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsMutex(Boolean, String, Boolean)Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.
Public methodMutex(Boolean, String, Boolean, MutexSecurity)Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.
Top

  NameDescription
Public propertySupported by the XNA FrameworkHandle Obsolete. Gets or sets the native operating system handle. (Inherited from WaitHandle.)
Public propertySafeWaitHandleGets or sets the native operating system handle. (Inherited from WaitHandle.)
Top

  NameDescription
Public methodSupported by the XNA FrameworkCloseReleases all resources held by the current WaitHandle. (Inherited from WaitHandle.)

In XNA Framework, this member is overridden by Close().
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsDispose()Releases all resources used by the current instance of the WaitHandle class. (Inherited from WaitHandle.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetAccessControlGets a MutexSecurity object that represents the access control security for the named mutex.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsOpenExisting(String)Opens the specified named mutex, if it already exists.
Public methodStatic memberOpenExisting(String, MutexRights)Opens the specified named mutex, if it already exists, with the desired security access.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsReleaseMutexReleases the Mutex once.
Public methodSetAccessControlSets the access control security for a named system mutex.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodStatic memberSupported in .NET for Windows Store appsTryOpenExisting(String, Mutex)Opens the specified named mutex, if it already exists, and returns a value that indicates whether the operation succeeded.
Public methodStatic memberTryOpenExisting(String, MutexRights, Mutex)Opens the specified named mutex, if it already exists, with the desired security access, and returns a value that indicates whether the operation succeeded.
Public methodSupported by the XNA FrameworkWaitOne()Blocks the current thread until the current WaitHandle receives a signal. (Inherited from WaitHandle.)

In XNA Framework, this member is overridden by WaitOne().
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitOne(Int32)Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval. (Inherited from WaitHandle.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsWaitOne(TimeSpan)Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval. (Inherited from WaitHandle.)
Public methodSupported by the XNA FrameworkWaitOne(Int32, Boolean)Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval and specifying whether to exit the synchronization domain before the wait. (Inherited from WaitHandle.)

In XNA Framework, this member is overridden by WaitOne(Int32, Boolean).
Public methodWaitOne(TimeSpan, Boolean)Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait. (Inherited from WaitHandle.)
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIDisposable.DisposeInfrastructure. Releases all resources used by the WaitHandle. (Inherited from WaitHandle.)
Top

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.

Important noteImportant

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.

You can use the WaitHandle.WaitOne method to request ownership of a mutex. The calling thread blocks until one of the following occurs:

  • The mutex is signaled to indicate that it is not owned. When this happens, the WaitOne method returns true, and the calling thread assumes ownership of the mutex and accesses the resource protected by the mutex. When it has finished accessing the resource, the thread must call the ReleaseMutex method to release ownership of the mutex. The first example in the Examples section illustrates this pattern.

  • The time-out interval specified in the call to a WaitOne method that has a millisecondsTimeout or timeout parameter has elapsed. When this happens, the WaitOne method returns false, and the calling thread makes no further attempt to acquire ownership of the mutex. In this case, you should structure your code so that access to the resource that is protected by the mutex is denied to the calling thread. Because the thread never acquired ownership of the mutex, it must not call the ReleaseMutex method. The second example in the Examples section illustrates this pattern.

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity. A mutex can also be passed across application domain boundaries.

The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex.

Because the Mutex class inherits from WaitHandle, you can also call the static WaitHandle.WaitAll and WaitHandle.WaitAny methods to synchronize access to a protected resource.

If a thread terminates while owning a mutex, the mutex is said to be abandoned. The state of the mutex is set to signaled, and the next waiting thread gets ownership. Beginning in version 2.0 of the .NET Framework, an AbandonedMutexException is thrown in the next thread that acquires the abandoned mutex. Before version 2.0 of the .NET Framework, no exception was thrown.

Caution noteCaution

An abandoned mutex often indicates a serious error in the code. When a thread exits without releasing the mutex, the data structures protected by the mutex might not be in a consistent state. The next thread to request ownership of the mutex can handle this exception and proceed, if the integrity of the data structures can be verified.

In the case of a system-wide mutex, an abandoned mutex might indicate that an application has been terminated abruptly (for example, by using Windows Task Manager).

Mutexes are of two types: local mutexes, which are unnamed, and named system mutexes. A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the Mutex object that represents the mutex. Each unnamed Mutex object represents a separate local mutex.

Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name. The operating-system object can be created at the same time, or it can exist before the creation of the Mutex object. You can create multiple Mutex objects that represent the same named system mutex, and you can use the OpenExisting method to open an existing named system mutex.

NoteNote

On a server that is running Terminal Services, a named system mutex can have two levels of visibility. If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.

In the following example, each thread calls the WaitOne(Int32) method to acquire the mutex. If the time-out interval elapses, the method returns false, and the thread neither acquires the mutex nor gains access to the resource the mutex protects. The ReleaseMutex method is called only by the thread that acquires the mutex.

using System;
using System.Threading;

class Example
{
    // Create a new Mutex. The creating thread does not own the mutex. 
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource. 
        for(int i = 0; i < numThreads; i++)
        {
            Thread newThread = new Thread(new ThreadStart(ThreadProc));
            newThread.Name = String.Format("Thread{0}", i + 1);
            newThread.Start();
        }

        // The main thread exits, but the application continues to 
        // run until all foreground threads have exited.
    }

    private static void ThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized 
    // so that only one thread at a time can enter. 
    private static void UseResource()
    {
        // Wait until it is safe to enter, and do not enter if the request times out.
        Console.WriteLine("{0} is requesting the mutex", Thread.CurrentThread.Name);
        if (mut.WaitOne(1000)) {
           Console.WriteLine("{0} has entered the protected area", 
               Thread.CurrentThread.Name);

           // Place code to access non-reentrant resources here. 

           // Simulate some work.
           Thread.Sleep(5000);

           Console.WriteLine("{0} is leaving the protected area", 
               Thread.CurrentThread.Name);

           // Release the Mutex.
              mut.ReleaseMutex();
           Console.WriteLine("{0} has released the mutex", 
                             Thread.CurrentThread.Name);
        }
        else {
           Console.WriteLine("{0} will not acquire the mutex", 
                             Thread.CurrentThread.Name);
        }
    }
}
// The example displays output like the following: 
//       Thread1 is requesting the mutex 
//       Thread1 has entered the protected area 
//       Thread2 is requesting the mutex 
//       Thread3 is requesting the mutex 
//       Thread2 will not acquire the mutex 
//       Thread3 will not acquire the mutex 
//       Thread1 is leaving the protected area 
//       Thread1 has released the mutex

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft