Export (0) Print
Expand All

Semaphore Constructor (Int32, Int32, String, Boolean%, SemaphoreSecurity)

Initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries, optionally reserving some entries for the calling thread, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

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

public:
Semaphore(
	int initialCount, 
	int maximumCount, 
	String^ name, 
	[OutAttribute] bool% createdNew, 
	SemaphoreSecurity^ semaphoreSecurity
)

Parameters

initialCount
Type: System::Int32

The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Type: System::Int32

The maximum number of requests for the semaphore that can be satisfied concurrently.

name
Type: System::String

The name of a named system semaphore object.

createdNew
Type: System::Boolean%

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

semaphoreSecurity
Type: System.Security.AccessControl::SemaphoreSecurity

A SemaphoreSecurity object that represents the access control security to be applied to the named system semaphore.

ExceptionCondition
ArgumentException

initialCount is greater than maximumCount.

-or-

name is longer than 260 characters.

ArgumentOutOfRangeException

maximumCount is less than 1.

-or-

initialCount is less than 0.

UnauthorizedAccessException

The named semaphore exists and has access control security, and the user does not have SemaphoreRights::FullControl.

IOException

A Win32 error occurred.

WaitHandleCannotBeOpenedException

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

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

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

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

NoteNote

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

If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. Use the createdNew parameter to determine whether the system semaphore was created by this constructor.

If initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

If you specify nullptr or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. In this case, createdNew is always true.

Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

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.dll>
using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::UnmanagedCode)]
   static void main()
   {
      String^ semaphoreName = L"SemaphoreExample5";

      Semaphore^ sem = nullptr;
      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^ ex ) 
      {
         Console::WriteLine( L"Semaphore does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"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 = String::Concat( Environment::UserDomainName,
            L"\\", Environment::UserName );
         SemaphoreSecurity^ semSec = gcnew SemaphoreSecurity;

         SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               SemaphoreRights::Synchronize |
               SemaphoreRights::Modify ),
            AccessControlType::Deny );
         semSec->AddAccessRule( rule );

         rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               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 = gcnew 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 )
         {
            Console::WriteLine( L"Created the semaphore." );
         }
         else
         {
            Console::WriteLine( L"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,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::ReadPermissions |
                  SemaphoreRights::ChangePermissions ));

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

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );

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

            // Now grant the user the correct rights. 
            //
            rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Allow );
            semSec->AddAccessRule( rule );

            // Update the ACL. This requires 
            // SemaphoreRights.ChangePermissions.
            sem->SetAccessControl( semSec );

            Console::WriteLine( L"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( L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }

      // Enter the semaphore, and hold it until the program 
      // exits. 
      // 
      try
      {
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore." );
         Console::WriteLine( L"Press the Enter key to exit." );
         Console::ReadLine();
         sem->Release();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
   }
};

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

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