Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Semaphore.OpenExisting Method (String, SemaphoreRights)

Opens an existing named semaphore, specifying the desired security access rights.

Namespace:  System.Threading
Assembly:  System (in System.dll)
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static Semaphore OpenExisting(
	string name,
	SemaphoreRights rights
)

Parameters

name
Type: System.String

The name of a system semaphore.

rights
Type: System.Security.AccessControl.SemaphoreRights

A bitwise combination of the SemaphoreRights values that represent the desired security access rights.

Return Value

Type: System.Threading.Semaphore
A Semaphore object that represents the named system semaphore.
ExceptionCondition
ArgumentException

name is an empty string.

-or-

name is longer than 260 characters.

ArgumentNullException

name is null.

WaitHandleCannotBeOpenedException

The named semaphore does not exist.

IOException

A Win32 error occurred.

UnauthorizedAccessException

The named semaphore exists, but the user does not have the desired security access rights.

The rights parameter must include SemaphoreRights.Synchronize to allow threads to enter the semaphore and SemaphoreRights.Modify to allow threads to call the Release method.

The OpenExisting method attempts to open only existing named semaphores. If a system semaphore with the specified name does not exist, this method throws an exception instead of creating the system semaphore.

It is possible to create multiple Semaphore objects that represent the same named system semaphore. Two calls to this method with the same value for name do not necessarily return the same Semaphore object, even though the objects returned both represent the same named system semaphore.

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 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. 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. If you run the compiled example from a third command window, it runs using the new permissions.

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // Attempt to open the named semaphore. 
        try
        {
            // Open the semaphore with (SemaphoreRights.Synchronize 
            // | SemaphoreRights.Modify), to enter and release the 
            // named semaphore. 
            //
            sem = Semaphore.OpenExisting(semaphoreName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Semaphore does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // 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)
        {
            // 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. 
            // 
            bool semaphoreWasCreated;

            // 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. 
            //
            string user = Environment.UserDomainName + "\\" 
                + Environment.UserName;
            SemaphoreSecurity semSec = new SemaphoreSecurity();

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | 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, 
                out 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)
            {
                Console.WriteLine("Created the semaphore.");
            }
            else
            {
                Console.WriteLine("Unable to create the semaphore.");
                return;
            }

        }
        else if (unauthorized)
        {
            // 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 
                        | SemaphoreRights.ChangePermissions);

                // Get the current ACL. This requires  
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();

                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user  
                // the right to enter and release the semaphore must 
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights. 
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | 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  
                // | SemaphoreRights.Modify), the rights required to 
                // enter and release the semaphore. 
                //
                sem = Semaphore.OpenExisting(semaphoreName);

            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // 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(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.