Export (0) Print
Expand All

Mutex.ReleaseMutex Method

Releases the Mutex once.

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

public void ReleaseMutex()

ExceptionCondition
ApplicationException

The calling thread does not own the mutex.

Whenever a thread acquires a mutex (for example, by calling its WaitOne method), it must subsequently call ReleaseMutex to relinquish ownership of the mutex and unblock other threads that are trying to gain ownership of the mutex. If the attempt to get ownership of the mutex fails (for example, when a call to the WaitOne method with a millisecondsTimeout or a timeout parameter returns false because the request times out), the thread shouldn't call ReleaseMutex, In this case, the thread should also not be allowed to access the resource protected by the mutex, as the following example shows.

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

A thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution. The number of calls is kept by the common language runtime. The thread must call ReleaseMutex the same number of times to release ownership of the mutex.

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. If no one owns the mutex, the state of the mutex is signaled. Beginning in version 2.0 of the .NET Framework, an AbandonedMutexException is thrown in the next thread that acquires the mutex. Prior to 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).

The following example shows how a local Mutex object is used to synchronize access to a protected resource. The thread that creates the mutex does not own it initially. The ReleaseMutex method is used to release the mutex when it is no longer needed.

// This example shows how a Mutex is used to synchronize access 
// to a protected resource. Unlike Monitor, Mutex can be used with 
// WaitHandle.WaitAll and WaitAny, and can be passed across 
// AppDomain boundaries. 

using System;
using System.Threading;

class Test
{
    // 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 myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

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

    private static void MyThreadProc()
    {
        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.
        mut.WaitOne();

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

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

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

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

        // Release the Mutex.
        mut.ReleaseMutex();
    }
}

.NET Framework

Supported in: 4.6, 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

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: 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.

Show:
© 2014 Microsoft