Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Semaphore.OpenExisting Method (String)

Opens the specified named semaphore, if it already exists.

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

'Declaration
Public Shared Function OpenExisting ( _
	name As String _
) As Semaphore

Parameters

name
Type: System.String

The name of the system semaphore to open.

Return Value

Type: System.Threading.Semaphore
An object that represents the named system semaphore.

ExceptionCondition
ArgumentException

name is an empty string.

-or-

name is longer than 260 characters.

ArgumentNullException

name is Nothing.

WaitHandleCannotBeOpenedException

The named semaphore does not exist.

IOException

A Win32 error occurred.

UnauthorizedAccessException

The named semaphore exists, but the user does not have the security access required to use it.

The OpenExisting method tries to open the specified named semaphore. If the system semaphore does not exist, this method throws an exception instead of creating the system semaphore. To create the system semaphore when it does not already exist, use one of the Semaphore constructors that has a name parameter.

Multiple calls to this method that use the same value for name do not necessarily return the same Semaphore object, even though the objects that are returned represent the same named system semaphore.

This method overload is equivalent to calling the OpenExisting method overload and specifying SemaphoreRights.Synchronize and SemaphoreRights.Modify rights, combined by using the bitwise OR operation.

Specifying the SemaphoreRights.Synchronize flag allows a thread to enter the semaphore, and specifying the SemaphoreRights.Modify flag allows a thread to call the Release method.

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

If the semaphore does not exist, it is created with a maximum count of two and with access control security that denies the current user the right to use the semaphore, but which grants the right to read and change permissions on the semaphore.

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

After the permissions are changed, the semaphore 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 semaphoreName As String = "SemaphoreExample5" 

        Dim sem As Semaphore = Nothing 
        Dim doesNotExist as Boolean = False 
        Dim unauthorized As Boolean = False 

        ' Attempt to open the named semaphore. 
        Try 
            ' Open the semaphore with (SemaphoreRights.Synchronize 
            ' Or SemaphoreRights.Modify), to enter and release the 
            ' named semaphore. 
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore 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 semaphore does not exist. 
        ' (2) The semaphore exists, but the current user doesn't  
        ' have access. (3) The semaphore exists and the user has 
        ' access. 
        
        If doesNotExist Then 
            ' The semaphore does not exist, so create it. 
            
            ' The value of this variable is set by the semaphore 
            ' constructor. It is True if the named system semaphore was 
            ' created, and False if the named semaphore already existed. 
            
            Dim semaphoreWasCreated As Boolean 

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

            Dim rule As New SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system 
            ' semaphore named by the constant 'semaphoreName', with 
            ' maximum count three, initial count three, and the 
            ' specified security access. The Boolean value that  
            ' indicates creation of the underlying system object is 
            ' placed in semaphoreWasCreated. 
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

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

        ElseIf unauthorized Then 

            ' Open the semaphore to read and change the access 
            ' control security. The access control security defined 
            ' above allows the current user to do this. 
            
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires  
                ' SemaphoreRights.ReadPermissions. 
                Dim semSec As SemaphoreSecurity = sem.GetAccessControl()

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

                ' First, the rule that denied the current user  
                ' the right to enter and release the semaphore must 
                ' be removed. 
                Dim rule As New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights. 
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires 
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize  
                ' Or SemaphoreRights.Modify), the rights required to 
                ' enter and release the semaphore. 
                '
                sem = Semaphore.OpenExisting(semaphoreName)

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

        End If 

        ' Enter the semaphore, and hold it until the program 
        ' exits. 
        
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        End Try 
    End Sub  
End Class

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

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

Portable Class Library

Supported in: Portable Class Library

Show:
© 2015 Microsoft