Semaphore.OpenExisting Yöntem

Tanım

Zaten varsa belirtilen bir adlandırılmış semaforu açar.Opens a specified named semaphore, if it already exists.

Aşırı Yüklemeler

OpenExisting(String)

Zaten varsa belirtilen adlandırılmış semaforu açar.Opens the specified named semaphore, if it already exists.

OpenExisting(String, SemaphoreRights)

Zaten varsa, istenen güvenlik erişimiyle birlikte belirtilen adlandırılmış semaforu açar.Opens the specified named semaphore, if it already exists, with the desired security access.

OpenExisting(String)

Zaten varsa belirtilen adlandırılmış semaforu açar.Opens the specified named semaphore, if it already exists.

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name);
public static System.Threading.Semaphore OpenExisting (string name);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.Semaphore OpenExisting (string name);
static member OpenExisting : string -> System.Threading.Semaphore
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String) As Semaphore

Parametreler

name
String

Diğer işlemlerle paylaşılacak eşitleme nesnesinin adı.The name of the synchronization object to be shared with other processes. Bu ad büyük/küçük harfe duyarlıdır.The name is case-sensitive.

Döndürülenler

Semaphore

Adlandırılmış sistem semaforu temsil eden nesne.An object that represents the named system semaphore.

Öznitelikler

Özel durumlar

name boş bir dizedir.name is an empty string.

-veya--or-

Yalnızca .NET Framework: name MAX_PATH (260 karakter) daha uzun..NET Framework only: name is longer than MAX_PATH (260 characters).

name, null değeridir.name is null.

Sağlanmış bir eşitleme nesnesi oluşturulamıyor name .A synchronization object with the provided name cannot be created. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.A synchronization object of a different type might have the same name. Bazı durumlarda, bu özel durum geçersiz adlar için oluşturulabilir.In some cases, this exception may be thrown for invalid names.

name geçersizdir.name is invalid. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilecek bazı kısıtlamalar dahil çeşitli nedenlerle olabilir.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. "Genel " ve" yerel ön eklerinin " büyük/küçük harfe duyarlı olduğunu unutmayın.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-veya--or-

Başka bir hata oluştu.There was some other error. HResultÖzelliği daha fazla bilgi verebilir.The HResult property may provide more information.

nameÇok uzun.The name is too long. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.Length restrictions may depend on the operating system or configuration.

Adlandırılmış semafor var, ancak kullanıcının onu kullanmak için gerekli güvenlik erişimi yok.The named semaphore exists, but the user does not have the security access required to use it.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliği ile adlandırılmış semaforun çapraz işlem davranışını gösterir.The following code example demonstrates the cross-process behavior of a named semaphore with access control security. Örnek, OpenExisting(String) adlandırılmış semaforun varlığını test etmek için yöntem aşırı yüklemesini kullanır.The example uses the OpenExisting(String) method overload to test for the existence of a named semaphore.

Semafor yoksa, en fazla iki sayısıyla ve erişim denetimi güvenliği ile oluşturulur ve bu, geçerli kullanıcıya semaforu kullanma hakkını reddeder, ancak semafor üzerinde izinleri okuma ve değiştirme hakkını verir.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.

Derlenmiş örneği iki komut penceresinden çalıştırırsanız ikinci kopya, yöntem aşırı yüküne yapılan çağrıda bir erişim ihlali özel durumu oluşturur OpenExisting(String) .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. Özel durum yakalandı ve örnekte, OpenExisting(String, SemaphoreRights) izinleri okumak ve değiştirmek için gereken haklara sahip semaforu açmak için yöntem aşırı yüklemesi kullanılır.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.

İzinler değiştirildikten sonra, semafor girmek ve serbest bırakmak için gereken haklara sahip semafor açılır.After the permissions are changed, the semaphore is opened with the rights required to enter and release it. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinleri kullanarak çalışır.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 );
      }
   }
};
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);
        }
    }
}
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 

Açıklamalar

, name Global\ Local\ Bir ad alanı belirtmek için veya öneki olabilir.The name may be prefixed with Global\ or Local\ to specify a namespace. GlobalAd alanı belirtildiğinde, eşitleme nesnesi sistemde herhangi bir işlemle paylaşılabilir.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Ad alanı belirtildiğinde Local , ad alanı belirtilmediğinde de varsayılan değer olan eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. Windows 'da, oturum bir oturum açma oturumununlardır ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır.On Windows, a session is a login session, and services typically run in a different non-interactive session. UNIX benzeri işletim sistemlerinde, her kabuğun kendi oturumu vardır.On Unix-like operating systems, each shell has its own session. Oturum-yerel eşitleme nesneleri, hepsi aynı oturumda çalıştıkları bir üst/alt ilişkisi olan süreçler arasında eşitlemeye uygun olabilir.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Windows 'da nesne adlarını eşitleme hakkında daha fazla bilgi için bkz. nesne adları.For more information about synchornization object names on Windows, see Object Names.

İstenen türdeki bir eşitleme nesnesi ad alanında varsa, varolan eşitleme nesnesi açılır.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. Bir eşitleme nesnesi ad alanında yoksa veya ad alanında farklı türde bir eşitleme nesnesi varsa, bir oluşturulur WaitHandleCannotBeOpenedException .If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

OpenExistingYöntemi belirtilen adlandırılmış semaforu açmaya çalışır.The OpenExisting method tries to open the specified named semaphore. Zaten mevcut olmadığında sistem semaforu oluşturmak için, Semaphore bir parametreye sahip olan oluşturuculardan birini kullanın name .To create the system semaphore when it does not already exist, use one of the Semaphore constructors that has a name parameter.

İçin aynı değeri kullanan Bu metoda yönelik birden çok çağrı aynı name nesneyi döndürmemelidir Semaphore , ancak döndürülen nesneler aynı adlı sistem semaforu temsil eder.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.

Bu yöntem aşırı yüklemesi, OpenExisting yöntem aşırı yüklemesini çağırmaya ve SemaphoreRights.Synchronize SemaphoreRights.Modify bit düzeyinde OR işlemi kullanılarak birleştirilen ve hakların belirtilmesine eşdeğerdir.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.

Bayrak belirtildiğinde SemaphoreRights.Synchronize bir iş parçacığının semafor girmesini sağlar ve SemaphoreRights.Modify bayrağın belirlenmesi bir iş parçacığının yöntemi çağırmasını sağlar Release .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.

Şunlara uygulanır

OpenExisting(String, SemaphoreRights)

Zaten varsa, istenen güvenlik erişimiyle birlikte belirtilen adlandırılmış semaforu açar.Opens the specified named semaphore, if it already exists, with the desired security access.

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Security::AccessControl::SemaphoreRights rights);
public static System.Threading.Semaphore OpenExisting (string name, System.Security.AccessControl.SemaphoreRights rights);
static member OpenExisting : string * System.Security.AccessControl.SemaphoreRights -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, rights As SemaphoreRights) As Semaphore

Parametreler

name
String

Diğer işlemlerle paylaşılacak eşitleme nesnesinin adı.The name of the synchronization object to be shared with other processes. Bu ad büyük/küçük harfe duyarlıdır.The name is case-sensitive.

rights
SemaphoreRights

İstenen güvenlik erişimini temsil eden sabit listesi değerlerinin bit düzeyinde birleşimi.A bitwise combination of the enumeration values that represent the desired security access.

Döndürülenler

Semaphore

Adlandırılmış sistem semaforu temsil eden nesne.An object that represents the named system semaphore.

Özel durumlar

name boş bir dizedir.name is an empty string.

-veya--or-

Yalnızca .NET Framework: name MAX_PATH (260 karakter) daha uzun..NET Framework only: name is longer than MAX_PATH (260 characters).

name, null değeridir.name is null.

Sağlanmış bir eşitleme nesnesi oluşturulamıyor name .A synchronization object with the provided name cannot be created. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.A synchronization object of a different type might have the same name. Bazı durumlarda, bu özel durum geçersiz adlar için oluşturulabilir.In some cases, this exception may be thrown for invalid names.

name geçersizdir.name is invalid. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilecek bazı kısıtlamalar dahil çeşitli nedenlerle olabilir.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. "Genel " ve" yerel ön eklerinin " büyük/küçük harfe duyarlı olduğunu unutmayın.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-veya--or-

Başka bir hata oluştu.There was some other error. HResultÖzelliği daha fazla bilgi verebilir.The HResult property may provide more information.

nameÇok uzun.The name is too long. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.Length restrictions may depend on the operating system or configuration.

Adlandırılmış semafor var, ancak kullanıcı istenen güvenlik erişimi haklarına sahip değil.The named semaphore exists, but the user does not have the desired security access rights.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliği ile adlandırılmış semaforun çapraz işlem davranışını gösterir.The following code example demonstrates the cross-process behavior of a named semaphore with access control security. Örnek, OpenExisting(String) adlandırılmış semaforun varlığını test etmek için yöntem aşırı yüklemesini kullanır.The example uses the OpenExisting(String) method overload to test for the existence of a named semaphore.

Semafor yoksa, en fazla iki sayısıyla ve erişim denetimi güvenliği ile oluşturulur ve bu, geçerli kullanıcıya semaforu kullanma hakkını reddeder, ancak semafor üzerinde izinleri okuma ve değiştirme hakkını verir.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.

Derlenmiş örneği iki komut penceresinden çalıştırırsanız ikinci kopya yöntemine yapılan çağrıda bir erişim ihlali özel durumu oluşturur OpenExisting(String) .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. Özel durum yakalandı ve örnekte, OpenExisting(String, SemaphoreRights) izinleri okumak ve değiştirmek için gereken haklara sahip semaforu açmak için yöntem aşırı yüklemesi kullanılır.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.

İzinler değiştirildikten sonra, semafor girmek ve serbest bırakmak için gereken haklara sahip semafor açılır.After the permissions are changed, the semaphore is opened with the rights required to enter and release it. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinleri kullanarak çalışır.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 );
      }
   }
};
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);
        }
    }
}
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 

Açıklamalar

, name Global\ Local\ Bir ad alanı belirtmek için veya öneki olabilir.The name may be prefixed with Global\ or Local\ to specify a namespace. GlobalAd alanı belirtildiğinde, eşitleme nesnesi sistemde herhangi bir işlemle paylaşılabilir.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Ad alanı belirtildiğinde Local , ad alanı belirtilmediğinde de varsayılan değer olan eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. Windows 'da, oturum bir oturum açma oturumununlardır ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır.On Windows, a session is a login session, and services typically run in a different non-interactive session. UNIX benzeri işletim sistemlerinde, her kabuğun kendi oturumu vardır.On Unix-like operating systems, each shell has its own session. Oturum-yerel eşitleme nesneleri, hepsi aynı oturumda çalıştıkları bir üst/alt ilişkisi olan süreçler arasında eşitlemeye uygun olabilir.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Windows 'da nesne adlarını eşitleme hakkında daha fazla bilgi için bkz. nesne adları.For more information about synchornization object names on Windows, see Object Names.

İstenen türdeki bir eşitleme nesnesi ad alanında varsa, varolan eşitleme nesnesi açılır.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. Bir eşitleme nesnesi ad alanında yoksa veya ad alanında farklı türde bir eşitleme nesnesi varsa, bir oluşturulur WaitHandleCannotBeOpenedException .If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

rightsParametresi, SemaphoreRights.Synchronize iş parçacıklarının semaforu girmesine izin veren bayrağını ve SemaphoreRights.Modify iş parçacıklarının yöntemi çağırabileceği bayrağı içermelidir Release .The rights parameter must include the SemaphoreRights.Synchronize flag to allow threads to enter the semaphore, and the SemaphoreRights.Modify flag to allow threads to call the Release method.

OpenExistingYöntemi, mevcut bir adlandırılmış semaforu açmaya çalışır.The OpenExisting method tries to open an existing named semaphore. Zaten mevcut olmadığında sistem semaforu oluşturmak için, Semaphore bir parametreye sahip olan oluşturuculardan birini kullanın name .To create the system semaphore when it does not already exist, use one of the Semaphore constructors that has a name parameter.

İçin aynı değeri kullanan Bu metoda yönelik birden çok çağrı aynı name nesneyi döndürmemelidir Semaphore , ancak döndürülen nesneler aynı adlı sistem semaforu temsil eder.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.

Şunlara uygulanır