Export (0) Print
Expand All

Mutex Constructor (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.

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

'Declaration
Public Sub New ( _
	initiallyOwned As Boolean, _
	name As String, _
	<OutAttribute> ByRef createdNew As Boolean, _
	mutexSecurity As MutexSecurity _
)

Parameters

initiallyOwned
Type: System.Boolean

true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
Type: System.String

The name of the system mutex. If the value is Nothing, the Mutex is unnamed.

createdNew
Type: System.Boolean

When this method returns, contains a Boolean that is true if a local mutex was created (that is, if name is Nothing or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. This parameter is passed uninitialized.

mutexSecurity
Type: System.Security.AccessControl.MutexSecurity

A MutexSecurity object that represents the access control security to be applied to the named system mutex.

ExceptionCondition
IOException

A Win32 error occurred.

UnauthorizedAccessException

The named mutex exists and has access control security, but the user does not have MutexRights.FullControl.

WaitHandleCannotBeOpenedException

The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

ArgumentException

name is longer than 260 characters.

If name is not Nothing and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. Otherwise the thread can request the mutex by calling the WaitOne method.

Use this constructor to apply access control security to a named system mutex when it is created, preventing other code from taking control of the mutex.

This constructor initializes a Mutex object that represents a named system mutex. You can create multiple Mutex objects that represent the same named system mutex.

If the named system mutex does not exist, it is created with the specified access control security. If the named mutex exists, the specified access control security is ignored.

NoteNote

The caller has full control over the newly created Mutex object even if mutexSecurity denies or fails to grant some access rights to the current user. However, if the current user attempts to get another Mutex object to represent the same named mutex, using either a constructor or the OpenExisting method, Windows access control security is applied.

If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

If you specify Nothing or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. In this case, createdNew is always true.

Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

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.

The following code example demonstrates the cross-process behavior of a named mutex with access control security. The example uses the OpenExisting(String) method overload to test for the existence of a named mutex.

If the mutex does not exist, it is created with initial ownership and access control security that denies the current user the right to use the mutex, but grants the right to read and change permissions on the mutex.

If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). The exception is caught, and the example uses the OpenExisting(String, MutexRights) method overload to open the mutex with the rights needed to read and change the permissions.

After the permissions are changed, the mutex is opened with the rights required to enter and release it. If you run the compiled example from a third command window, it runs using the new permissions.

Imports System
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4" 

        Dim m As Mutex = Nothing 
        Dim doesNotExist as Boolean = False 
        Dim unauthorized As Boolean = False 

        ' The value of this variable is set by the mutex 
        ' constructor. It is True if the named system mutex was 
        ' created, and False if the named mutex already existed. 
        
        Dim mutexWasCreated As Boolean 

        ' Attempt to open the named mutex. 
        Try 
            ' Open the mutex with (MutexRights.Synchronize Or 
            ' MutexRights.Modify), to enter and release the 
            ' named mutex. 
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True 
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True 
        End Try 

        ' There are three cases: (1) The mutex does not exist. 
        ' (2) The mutex exists, but the current user doesn't  
        ' have access. (3) The mutex exists and the user has 
        ' access. 
        
        If doesNotExist Then 
            ' The mutex does not exist, so create it. 

            ' Create an access control list (ACL) that denies the 
            ' current user the right to enter or release the  
            ' mutex, but allows the right to read and change 
            ' security information for the mutex. 
            
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim mSec As New MutexSecurity()

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system 
            ' mutex named by the constant 'mutexName', with 
            ' initial ownership for this thread, and with the 
            ' specified security access. The Boolean value that  
            ' indicates creation of the underlying system object 
            ' is placed in mutexWasCreated. 
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex was created, it can be 
            ' used by the current instance of this program, even  
            ' though the current user is denied access. The current 
            ' program owns the mutex. Otherwise, exit the program. 
            '  
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return 
            End If 

        ElseIf unauthorized Then 

            ' Open the mutex to read and change the access control 
            ' security. The access control security defined above 
            ' allows the current user to do this. 
            
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires  
                ' MutexRights.ReadPermissions. 
                Dim mSec As MutexSecurity = m.GetAccessControl()

                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user  
                ' the right to enter and release the mutex must 
                ' be removed. 
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights. 
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires 
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize  
                ' Or MutexRights.Modify), the rights required to 
                ' enter and release the mutex. 
                '
                m = Mutex.OpenExisting(mutexName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return 
            End Try 

        End If 

        ' If this program created the mutex, it already owns 
        ' the mutex. 
        
        If Not mutexWasCreated Then 
            ' Enter the mutex, and hold it until the program 
            ' exits. 
            
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try 
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
    End Sub  
End Class

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

  • SecurityCriticalAttribute 

    Requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

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