Semaphore Konstruktoren

Definition

Initialisiert eine neue Instanz der Semaphore-Klasse.

Überlädt

Semaphore(Int32, Int32)

Initialisiert eine neue Instanz der Semaphore-Klasse und gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen an.

Semaphore(Int32, Int32, String)

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen sowie optional den Namen eines Systemsemaphorobjekts an.

Semaphore(Int32, Int32, String, Boolean)

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen sowie optional den Namen eines Systemsemaphorobjekts an, gibt eine Variable an, die einen Wert empfängt, der angibt, ob ein neues Systemsemaphor erstellt wurde.

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

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen an, gibt optional den Namen eines Systemsemaphorobjekts an, gibt eine Variable an, die einen Wert empfängt, der angibt, ob ein neues Systemsemaphor erstellt wurde, und gibt die Sicherheitszugriffssteuerung für das Systemsemaphor an.

Semaphore(Int32, Int32)

Quelle:
Semaphore.cs
Quelle:
Semaphore.cs
Quelle:
Semaphore.cs

Initialisiert eine neue Instanz der Semaphore-Klasse und gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen an.

public:
 Semaphore(int initialCount, int maximumCount);
public Semaphore (int initialCount, int maximumCount);
new System.Threading.Semaphore : int * int -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer)

Parameter

initialCount
Int32

Die anfängliche Anzahl von Anforderungen für das Semaphor, die gleichzeitig gewährt werden können.

maximumCount
Int32

Die maximale Anzahl von Anforderungen für das Semaphor, die gleichzeitig gewährt werden können.

Ausnahmen

initialCount ist größer als maximumCount.

maximumCount ist kleiner als 1.

- oder -

initialCount ist kleiner als 0.

Beispiele

Im folgenden Beispiel wird ein Semaphor mit einer maximalen Anzahl von drei und einer anfänglichen Anzahl von 0 erstellt. Im Beispiel werden fünf Threads gestartet, die auf den Semaphor warten. Der Standard Thread verwendet die Release(Int32) Methodenüberladung, um die Semaphoranzahl auf das Maximum zu erhöhen, sodass drei Threads in das Semaphor gelangen können. Jeder Thread verwendet die Thread.Sleep -Methode, um eine Sekunde zu warten, die Arbeit zu simulieren, und ruft dann die Release() Methodenüberladung auf, um das Semaphor freizugeben. Jedes Mal, wenn der Semaphor freigesetzt wird, wird die vorherige Semaphoranzahl angezeigt. Konsolennachrichten verfolgen die Verwendung von Semaphoren nach. Das simulierte Arbeitsintervall wird für jeden Thread geringfügig erhöht, um die Ausgabe leichter zu lesen.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // A semaphore that simulates a limited resource pool.
   //
   static Semaphore^ _pool;

   // A padding interval to make the output more orderly.
   static int _padding;

public:
   static void Main()
   {
      // Create a semaphore that can satisfy up to three
      // concurrent requests. Use an initial count of zero,
      // so that the entire semaphore count is initially
      // owned by the main program thread.
      //
      _pool = gcnew Semaphore( 0,3 );
      
      // Create and start five numbered threads.
      //
      for ( int i = 1; i <= 5; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( Worker ) );
         
         // Start the thread, passing the number.
         //
         t->Start( i );
      }
      
      // Wait for half a second, to allow all the
      // threads to start and to block on the semaphore.
      //
      Thread::Sleep( 500 );
      
      // The main thread starts out holding the entire
      // semaphore count. Calling Release(3) brings the
      // semaphore count back to its maximum value, and
      // allows the waiting threads to enter the semaphore,
      // up to three at a time.
      //
      Console::WriteLine( L"Main thread calls Release(3)." );
      _pool->Release( 3 );

      Console::WriteLine( L"Main thread exits." );
   }

private:
   static void Worker( Object^ num )
   {
      // Each worker thread begins by requesting the
      // semaphore.
      Console::WriteLine( L"Thread {0} begins and waits for the semaphore.", num );
      _pool->WaitOne();
      
      // A padding interval to make the output more orderly.
      int padding = Interlocked::Add( _padding, 100 );

      Console::WriteLine( L"Thread {0} enters the semaphore.", num );
      
      // The thread's "work" consists of sleeping for
      // about a second. Each thread "works" a little
      // longer, just to make the output more orderly.
      //
      Thread::Sleep( 1000 + padding );

      Console::WriteLine( L"Thread {0} releases the semaphore.", num );
      Console::WriteLine( L"Thread {0} previous semaphore count: {1}",
         num, _pool->Release() );
   }
};
using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(initialCount: 0, maximumCount: 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(releaseCount: 3);

        Console.WriteLine("Main thread exits.");
    }

    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}
Imports System.Threading

Public Class Example

    ' A semaphore that simulates a limited resource pool.
    '
    Private Shared _pool As Semaphore

    ' A padding interval to make the output more orderly.
    Private Shared _padding As Integer

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a semaphore that can satisfy up to three
        ' concurrent requests. Use an initial count of zero,
        ' so that the entire semaphore count is initially
        ' owned by the main program thread.
        '
        _pool = New Semaphore(0, 3)

        ' Create and start five numbered threads. 
        '
        For i As Integer = 1 To 5
            Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
            'Dim t As New Thread(AddressOf Worker)

            ' Start the thread, passing the number.
            '
            t.Start(i)
        Next i

        ' Wait for half a second, to allow all the
        ' threads to start and to block on the semaphore.
        '
        Thread.Sleep(500)

        ' The main thread starts out holding the entire
        ' semaphore count. Calling Release(3) brings the 
        ' semaphore count back to its maximum value, and
        ' allows the waiting threads to enter the semaphore,
        ' up to three at a time.
        '
        Console.WriteLine("Main thread calls Release(3).")
        _pool.Release(3)

        Console.WriteLine("Main thread exits.")
    End Sub

    Private Shared Sub Worker(ByVal num As Object)
        ' Each worker thread begins by requesting the
        ' semaphore.
        Console.WriteLine("Thread {0} begins " _
            & "and waits for the semaphore.", num)
        _pool.WaitOne()

        ' A padding interval to make the output more orderly.
        Dim padding As Integer = Interlocked.Add(_padding, 100)

        Console.WriteLine("Thread {0} enters the semaphore.", num)
        
        ' The thread's "work" consists of sleeping for 
        ' about a second. Each thread "works" a little 
        ' longer, just to make the output more orderly.
        '
        Thread.Sleep(1000 + padding)

        Console.WriteLine("Thread {0} releases the semaphore.", num)
        Console.WriteLine("Thread {0} previous semaphore count: {1}", _
            num, _
            _pool.Release())
    End Sub
End Class

Hinweise

Dieser Konstruktor initialisiert einen unbenannten Semaphor. Alle Threads, die eine instance eines solchen Semaphors verwenden, müssen Verweise auf die instance haben.

Wenn initialCount kleiner als maximumCountist, ist der Effekt identisch mit dem, wenn der aktuelle Thread (maximumCountminus initialCount) mal aufgerufen WaitOne hat. Wenn Sie keine Einträge für den Thread reservieren möchten, der das Semaphor erstellt, verwenden Sie die gleiche Zahl für maximumCount und initialCount.

Weitere Informationen

Gilt für:

Semaphore(Int32, Int32, String)

Quelle:
Semaphore.cs
Quelle:
Semaphore.cs
Quelle:
Semaphore.cs

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen sowie optional den Namen eines Systemsemaphorobjekts an.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name);
public Semaphore (int initialCount, int maximumCount, string name);
public Semaphore (int initialCount, int maximumCount, string? name);
new System.Threading.Semaphore : int * int * string -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String)

Parameter

initialCount
Int32

Die anfängliche Anzahl von Anforderungen für das Semaphor, die gleichzeitig gewährt werden können.

maximumCount
Int32

Die maximale Anzahl von Anforderungen für das Semaphor, die gleichzeitig gewährt werden können.

name
String

Der Name, wenn das Synchronisierungsobjekt für andere Prozesse freigegeben werden soll; andernfalls null oder eine leere Zeichenfolge. Bei dem Namen wird die Groß- und Kleinschreibung berücksichtigt. Der umgekehrte Schrägstrich (\) ist reserviert und kann nur zum Angeben eines Namespace verwendet werden. Weitere Informationen zu Namespaces finden Sie im Abschnitt Hinweise. Je nach Betriebssystem kann es weitere Einschränkungen für den Namen geben. Unter Unix-basierten Betriebssystemen muss der Name nach dem Ausschluss des Namespace beispielsweise ein gültiger Dateiname sein.

Ausnahmen

initialCount ist größer als maximumCount.

- oder -

Nur .NET Framework: name ist länger als MAX_PATH (260 Zeichen).

maximumCount ist kleiner als 1.

- oder -

initialCount ist kleiner als 0.

name ist ungültig. Dies kann aus verschiedenen Gründen der Fall sein, z. B. durch Einschränkungen, die vom Betriebssystem auferlegt werden, etwa ein unbekanntes Präfix oder ungültige Zeichen. Beachten Sie, dass bei dem Namen und den gängigen Präfixen "Global\" und "Local\" die Groß-/Kleinschreibung beachtet wird.

- oder -

Es ist ein anderer Fehler aufgetreten. DieHResult-Eigenschaft stellt möglicherweise weitere Informationen zur Verfügung.

Nur Windows: name hat einen unbekannten Namespace angegeben. Weitere Informationen finden Sie unter Objektnamen.

name ist zu lang. Längeneinschränkungen können vom Betriebssystem oder der Konfiguration abhängen.

Der benannte Semaphor ist vorhanden und verfügt über Zugriffssteuerungssicherheit, und der Benutzer verfügt nicht über FullControl.

Ein Synchronisierungsobjekt mit dem angegebenen name kann nicht erstellt werden. Ein Synchronisierungsobjekt eines anderen Typs weist ggf. denselben Namen auf.

Beispiele

Im folgenden Codebeispiel wird das prozessübergreifende Verhalten eines benannten Semaphors veranschaulicht. Im Beispiel wird ein benannter Semaphor mit einer maximalen Anzahl von fünf und einer anfänglichen Anzahl von fünf erstellt. Das Programm führt drei Aufrufe an die WaitOne -Methode aus. Wenn Sie also das kompilierte Beispiel aus zwei Befehlsfenstern ausführen, wird die zweite Kopie beim dritten Aufruf von WaitOneblockiert. Geben Sie einen oder mehrere Einträge in der ersten Kopie des Programms frei, um die Blockierung des zweiten Programms aufzuheben.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // Create a Semaphore object that represents the named
      // system semaphore "SemaphoreExample3". The semaphore has a
      // maximum count of five. The initial count is also five.
      // There is no point in using a smaller initial count,
      // because the initial count is not used if this program
      // doesn't create the named system semaphore, and with
      // this method overload there is no way to tell. Thus, this
      // program assumes that it is competing with other
      // programs for the semaphore.
      //
      Semaphore^ sem = gcnew Semaphore( 5,5,L"SemaphoreExample3" );
      
      // Attempt to enter the semaphore three times. If another
      // copy of this program is already running, only the first
      // two requests can be satisfied. The third blocks. Note
      // that in a real application, timeouts should be used
      // on the WaitOne calls, to avoid deadlocks.
      //
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore once." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore twice." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore three times." );
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(),n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");

        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    }
}
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample3". The semaphore has a
        ' maximum count of five. The initial count is also five. 
        ' There is no point in using a smaller initial count,
        ' because the initial count is not used if this program
        ' doesn't create the named system semaphore, and with 
        ' this method overload there is no way to tell. Thus, this
        ' program assumes that it is competing with other
        ' programs for the semaphore.
        '
        Dim sem As New Semaphore(5, 5, "SemaphoreExample3")

        ' Attempt to enter the semaphore three times. If another 
        ' copy of this program is already running, only the first
        ' two requests can be satisfied. The third blocks. Note 
        ' that in a real application, timeouts should be used
        ' on the WaitOne calls, to avoid deadlocks.
        '
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore once.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore twice.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore three times.")

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class

Hinweise

Dieser Konstruktor initialisiert ein Semaphore -Objekt, das einen benannten System-Semaphor darstellt. Sie können mehrere Semaphore Objekte erstellen, die denselben benannten System-Semaphor darstellen.

Der name kann mit Global\ dem Präfix oder Local\ versehen sein, um einen Namespace anzugeben. Wenn der Global Namespace angegeben wird, kann das Synchronisierungsobjekt für alle Prozesse im System freigegeben werden. Wenn der Local Namespace angegeben ist, was auch der Standardwert ist, wenn kein Namespace angegeben wird, kann das Synchronisierungsobjekt für Prozesse in derselben Sitzung freigegeben werden. Unter Windows ist eine Sitzung eine Anmeldesitzung, und Dienste werden in der Regel in einer anderen nicht interaktiven Sitzung ausgeführt. Unter Unix-ähnlichen Betriebssystemen verfügt jede Shell über eine eigene Sitzung. Sitzungslokale Synchronisierungsobjekte eignen sich möglicherweise für die Synchronisierung zwischen Prozessen mit einer übergeordneten/untergeordneten Beziehung, bei der sie alle in derselben Sitzung ausgeführt werden. Weitere Informationen zu Synchronisierungsobjektnamen unter Windows finden Sie unter Objektnamen.

Wenn ein name bereitgestellt wird und bereits ein Synchronisierungsobjekt des angeforderten Typs im Namespace vorhanden ist, wird das vorhandene Synchronisierungsobjekt verwendet. Wenn im Namespace bereits ein Synchronisierungsobjekt eines anderen Typs vorhanden ist, wird ein WaitHandleCannotBeOpenedException ausgelöst. Andernfalls wird ein neues Synchronisierungsobjekt erstellt.

Wenn der benannte System-Semaphor nicht vorhanden ist, wird es mit der anfänglichen Anzahl und der maximalen Anzahl erstellt, die von und maximumCountangegeben wirdinitialCount. Wenn der benannte System-Semaphor bereits vorhanden initialCount ist und maximumCount nicht verwendet wird, obwohl ungültige Werte weiterhin Ausnahmen verursachen. Wenn Sie ermitteln müssen, ob ein benannter System-Semaphor erstellt wurde, verwenden Sie stattdessen die Semaphore(Int32, Int32, String, Boolean) Konstruktorüberladung.

Wichtig

Wenn Sie diese Konstruktorüberladung verwenden, wird empfohlen, die gleiche Zahl für initialCount und maximumCountanzugeben. Wenn initialCount kleiner als maximumCountist und ein benannter System-Semaphor erstellt wird, ist der Effekt identisch, als hätte der aktuelle Thread (maximumCount minus initialCount) mal aufgerufen WaitOne . Mit dieser Konstruktorüberladung gibt es jedoch keine Möglichkeit, zu bestimmen, ob ein benanntes System-Semaphor erstellt wurde.

Wenn Sie oder eine leere Zeichenfolge für nameangebennull, wird ein lokaler Semaphor erstellt, als hätten Sie die Semaphore(Int32, Int32) Konstruktorüberladung aufgerufen.

Da benannte Semaphore im gesamten Betriebssystem sichtbar sind, können sie verwendet werden, um die Ressourcennutzung über Prozessgrenzen hinweg zu koordinieren.

Wenn Sie herausfinden möchten, ob ein benanntes System-Semaphor vorhanden ist, verwenden Sie die OpenExisting -Methode. Die OpenExisting Methode versucht, ein vorhandenes benanntes Semaphor zu öffnen, und löst eine Ausnahme aus, wenn das System-Semaphor nicht vorhanden ist.

Achtung

Standardmäßig ist ein benannter Semaphor nicht auf den Benutzer beschränkt, der es erstellt hat. Andere Benutzer können das Semaphor möglicherweise öffnen und verwenden, einschließlich der Störung des Semaphors, indem sie das Semaphor mehrmals erwerben und nicht freigeben. Wenn Sie den Zugriff auf bestimmte Benutzer einschränken möchten, können Sie eine Konstruktorüberladung oder SemaphoreAcl einen verwenden und beim Erstellen des benannten Semaphors übergeben SemaphoreSecurity . Vermeiden Sie die Verwendung benannter Semaphore ohne Zugriffsbeschränkungen auf Systemen, auf denen möglicherweise nicht vertrauenswürdige Benutzer Code ausführen.

Weitere Informationen

Gilt für:

Semaphore(Int32, Int32, String, Boolean)

Quelle:
Semaphore.cs
Quelle:
Semaphore.cs
Quelle:
Semaphore.cs

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen sowie optional den Namen eines Systemsemaphorobjekts an, gibt eine Variable an, die einen Wert empfängt, der angibt, ob ein neues Systemsemaphor erstellt wurde.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew);
public Semaphore (int initialCount, int maximumCount, string? name, out bool createdNew);
new System.Threading.Semaphore : int * int * string * bool -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean)

Parameter

initialCount
Int32

Die ursprüngliche Anzahl von Anforderungen für das Semaphor, die gleichzeitig ausgeführt werden können.

maximumCount
Int32

Die maximale Anzahl von Anforderungen für das Semaphor, die gleichzeitig ausgeführt werden können.

name
String

Der Name, wenn das Synchronisierungsobjekt für andere Prozesse freigegeben werden soll; andernfalls null oder eine leere Zeichenfolge. Bei dem Namen wird die Groß- und Kleinschreibung berücksichtigt. Das umgekehrte Schrägstrichzeichen (\) ist reserviert und kann nur zum Angeben eines Namespace verwendet werden. Weitere Informationen zu Namespaces finden Sie im Abschnitt hinweise. Je nach Betriebssystem kann es weitere Einschränkungen für den Namen geben. Unter Unix-basierten Betriebssystemen muss beispielsweise der Name nach dem Ausschluss des Namespace ein gültiger Dateiname sein.

createdNew
Boolean

Enthält nach dem Beenden dieser Methode den Wert true, wenn ein lokales Semaphor erstellt wurde (d. h., wenn name gleich null oder eine leere Zeichenfolge ist) oder wenn das angegebene benannte Systemsemaphor erstellt wurde. Der Wert ist false, wenn das angegebene benannte Systemsemaphor bereits vorhanden war. Dieser Parameter wird nicht initialisiert übergeben.

Ausnahmen

initialCount ist größer als maximumCount.

- oder -

Nur .NET Framework: name ist länger als MAX_PATH (260 Zeichen).

maximumCount ist kleiner als 1.

- oder -

initialCount ist kleiner als 0.

name ist ungültig. Dies kann aus verschiedenen Gründen der Fall sein, z. B. durch Einschränkungen, die vom Betriebssystem auferlegt werden, etwa ein unbekanntes Präfix oder ungültige Zeichen. Beachten Sie, dass bei dem Namen und den allgemeinen Präfixen "Global\" und "Local\" die Groß-/Kleinschreibung beachtet wird.

- oder -

Es ist ein anderer Fehler aufgetreten. DieHResult-Eigenschaft stellt möglicherweise weitere Informationen zur Verfügung.

Nur Windows: name hat einen unbekannten Namespace angegeben. Weitere Informationen finden Sie unter Objektnamen.

name ist zu lang. Längeneinschränkungen können vom Betriebssystem oder der Konfiguration abhängen.

Der benannte Semaphor ist vorhanden und verfügt über Zugriffssteuerungssicherheit, und der Benutzer verfügt nicht über FullControl.

Ein Synchronisierungsobjekt mit dem angegebenen name kann nicht erstellt werden. Ein Synchronisierungsobjekt eines anderen Typs weist ggf. denselben Namen auf.

Beispiele

Im folgenden Codebeispiel wird das prozessübergreifende Verhalten eines benannten Semaphors veranschaulicht. Im Beispiel wird ein benannter Semaphor mit einer maximalen Anzahl von fünf und einer anfänglichen Anzahl von zwei erstellt. Das heißt, es reserviert drei Einträge für den Thread, der den Konstruktor aufruft. Wenn createNew ist false, führt das Programm drei Aufrufe an die WaitOne -Methode aus. Wenn Sie also das kompilierte Beispiel aus zwei Befehlsfenstern ausführen, wird die zweite Kopie beim dritten Aufruf von WaitOneblockiert. Geben Sie einen oder mehrere Einträge in der ersten Kopie des Programms frei, um die Blockierung des zweiten Programms aufzuheben.

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // 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 a Semaphore object that represents the named
      // system semaphore "SemaphoreExample". The semaphore has a
      // maximum count of five, and an initial count of two. The
      // Boolean value that indicates creation of the underlying
      // system object is placed in semaphoreWasCreated.
      //
      Semaphore^ sem = gcnew Semaphore( 2,5,L"SemaphoreExample",
         semaphoreWasCreated );
      if ( semaphoreWasCreated )
      {
         // If the named system semaphore was created, its count is
         // set to the initial count requested in the constructor.
         // In effect, the current thread has entered the semaphore
         // three times.
         //
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      else
      {
         // If the named system semaphore was not created,
         // attempt to enter it three times. If another copy of
         // this program is already running, only the first two
         // requests can be satisfied. The third blocks.
         //
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore once." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore twice." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(), n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // 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 a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", 
            out semaphoreWasCreated);

        if (semaphoreWasCreated)
        {
            // If the named system semaphore was created, its count is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else
        {      
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } 
}
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' 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 a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample". The semaphore has a
        ' maximum count of five, and an initial count of two. The
        ' Boolean value that indicates creation of the underlying 
        ' system object is placed in semaphoreWasCreated.
        '
        Dim sem As New Semaphore(2, 5, "SemaphoreExample", _
            semaphoreWasCreated)

        If semaphoreWasCreated Then
            ' If the named system semaphore was created, its count is
            ' set to the initial count requested in the constructor.
            ' In effect, the current thread has entered the semaphore
            ' three times.
            ' 
            Console.WriteLine("Entered the semaphore three times.")
        Else
            ' If the named system semaphore was not created,  
            ' attempt to enter it three times. If another copy of
            ' this program is already running, only the first two
            ' requests can be satisfied. The third blocks.
            '
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore once.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore twice.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore three times.")
        End If

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class

Hinweise

Kann name mit Global\ dem Präfix oder Local\ versehen werden, um einen Namespace anzugeben. Wenn der Global Namespace angegeben ist, kann das Synchronisierungsobjekt für alle Prozesse im System freigegeben werden. Wenn der Local Namespace angegeben wird, was auch der Standardwert ist, wenn kein Namespace angegeben wird, kann das Synchronisierungsobjekt für Prozesse in derselben Sitzung freigegeben werden. Unter Windows ist eine Sitzung eine Anmeldesitzung, und Dienste werden in der Regel in einer anderen nicht interaktiven Sitzung ausgeführt. Unter Unix-ähnlichen Betriebssystemen verfügt jede Shell über eine eigene Sitzung. Sitzungslokale Synchronisierungsobjekte eignen sich möglicherweise für die Synchronisierung zwischen Prozessen mit einer über-/untergeordneten Beziehung, in der sie alle in derselben Sitzung ausgeführt werden. Weitere Informationen zu Synchronisierungsobjektnamen unter Windows finden Sie unter Objektnamen.

Wenn ein name bereitgestellt wird und ein Synchronisierungsobjekt des angeforderten Typs bereits im Namespace vorhanden ist, wird das vorhandene Synchronisierungsobjekt verwendet. Wenn ein Synchronisierungsobjekt eines anderen Typs bereits im Namespace vorhanden ist, wird eine WaitHandleCannotBeOpenedException ausgelöst. Andernfalls wird ein neues Synchronisierungsobjekt erstellt.

Dieser Konstruktor initialisiert ein Semaphore -Objekt, das einen benannten Systemsemaphor darstellt. Sie können mehrere Semaphore Objekte erstellen, die denselben benannten Systemsemaphor darstellen.

Wenn der benannte Systemsemaphor nicht vorhanden ist, wird er mit der anfänglichen Anzahl und der maximalen Anzahl erstellt, die von und maximumCountangegeben wirdinitialCount. Wenn der benannte Systemsemaphor bereits vorhanden ist initialCount und maximumCount nicht verwendet wird, obwohl ungültige Werte weiterhin Ausnahmen verursachen. Verwenden Sie createdNew , um zu bestimmen, ob das Systemsemaphor erstellt wurde.

Wenn initialCount kleiner als maximumCountist und createdNew ist, ist trueder Effekt der gleiche, als hätte der aktuelle Thread (maximumCountminus initialCount) mal aufgerufen WaitOne .

Wenn Sie oder eine leere Zeichenfolge für nameangebennull, wird ein lokaler Semaphor erstellt, als hätten Sie die Semaphore(Int32, Int32) Konstruktorüberladung aufgerufen. In diesem Fall createdNew ist immer true.

Da benannte Semaphore im gesamten Betriebssystem sichtbar sind, können sie verwendet werden, um die Ressourcennutzung über Prozessgrenzen hinweg zu koordinieren.

Achtung

Standardmäßig ist ein benannter Semaphor nicht auf den Benutzer beschränkt, der es erstellt hat. Andere Benutzer sind möglicherweise in der Lage, den Semaphor zu öffnen und zu verwenden, einschließlich der Interferenz mit dem Semaphor, indem sie den Semaphor mehrmals erwerben und nicht freigeben. Um den Zugriff auf bestimmte Benutzer einzuschränken, können Sie eine Konstruktorüberladung oder verwenden SemaphoreAcl und beim Erstellen des benannten Semaphors eine SemaphoreSecurity übergeben. Vermeiden Sie die Verwendung benannter Semaphore ohne Zugriffsbeschränkungen auf Systemen, auf denen möglicherweise nicht vertrauenswürdige Benutzer Code ausführen.

Weitere Informationen

Gilt für:

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

Initialisiert eine neue Instanz der Semaphore-Klasse, gibt die ursprüngliche Anzahl von Einträgen und die maximale Anzahl von gleichzeitigen Einträgen an, gibt optional den Namen eines Systemsemaphorobjekts an, gibt eine Variable an, die einen Wert empfängt, der angibt, ob ein neues Systemsemaphor erstellt wurde, und gibt die Sicherheitszugriffssteuerung für das Systemsemaphor an.

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::SemaphoreSecurity ^ semaphoreSecurity);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew, System.Security.AccessControl.SemaphoreSecurity semaphoreSecurity);
new System.Threading.Semaphore : int * int * string * bool * System.Security.AccessControl.SemaphoreSecurity -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean, semaphoreSecurity As SemaphoreSecurity)

Parameter

initialCount
Int32

Die ursprüngliche Anzahl von Anforderungen für das Semaphor, die gleichzeitig ausgeführt werden können.

maximumCount
Int32

Die maximale Anzahl von Anforderungen für das Semaphor, die gleichzeitig ausgeführt werden können.

name
String

Der Name, wenn das Synchronisierungsobjekt für andere Prozesse freigegeben werden soll; andernfalls null oder eine leere Zeichenfolge. Bei dem Namen wird die Groß- und Kleinschreibung berücksichtigt. Das umgekehrte Schrägstrichzeichen (\) ist reserviert und kann nur zum Angeben eines Namespace verwendet werden. Weitere Informationen zu Namespaces finden Sie im Abschnitt hinweise. Je nach Betriebssystem kann es weitere Einschränkungen für den Namen geben. Unter Unix-basierten Betriebssystemen muss beispielsweise der Name nach dem Ausschluss des Namespace ein gültiger Dateiname sein.

createdNew
Boolean

Enthält nach dem Beenden dieser Methode den Wert true, wenn ein lokales Semaphor erstellt wurde (d. h., wenn name gleich null oder eine leere Zeichenfolge ist) oder wenn das angegebene benannte Systemsemaphor erstellt wurde. Der Wert ist false, wenn das angegebene benannte Systemsemaphor bereits vorhanden war. Dieser Parameter wird nicht initialisiert übergeben.

semaphoreSecurity
SemaphoreSecurity

Ein SemaphoreSecurity-Objekt, das die Zugriffssteuerungssicherheit darstellt, die auf das benannte Systemsemaphor angewendet werden soll.

Ausnahmen

initialCount ist größer als maximumCount.

- oder -

Nur .NET Framework: name ist länger als MAX_PATH (260 Zeichen).

maximumCount ist kleiner als 1.

- oder -

initialCount ist kleiner als 0.

Der benannte Semaphor ist vorhanden und verfügt über Zugriffssteuerungssicherheit, und der Benutzer verfügt nicht über FullControl.

name ist ungültig. Dies kann aus verschiedenen Gründen der Fall sein, z. B. durch Einschränkungen, die vom Betriebssystem auferlegt werden, etwa ein unbekanntes Präfix oder ungültige Zeichen. Beachten Sie, dass bei dem Namen und den allgemeinen Präfixen "Global\" und "Local\" die Groß-/Kleinschreibung beachtet wird.

- oder -

Es ist ein anderer Fehler aufgetreten. DieHResult-Eigenschaft stellt möglicherweise weitere Informationen zur Verfügung.

Nur Windows: name hat einen unbekannten Namespace angegeben. Weitere Informationen finden Sie unter Objektnamen.

name ist zu lang. Längeneinschränkungen können vom Betriebssystem oder der Konfiguration abhängen.

Ein Synchronisierungsobjekt mit dem angegebenen name kann nicht erstellt werden. Ein Synchronisierungsobjekt eines anderen Typs weist ggf. denselben Namen auf.

Beispiele

Im folgenden Codebeispiel wird das prozessübergreifende Verhalten eines benannten Semaphors mit Zugriffssteuerungssicherheit veranschaulicht. Im Beispiel wird die OpenExisting(String) Methodenüberladung verwendet, um das Vorhandensein eines benannten Semaphors zu testen. Wenn der Semaphor nicht vorhanden ist, wird es mit einer maximalen Anzahl von zwei und mit Zugriffssteuerungssicherheit erstellt, die dem aktuellen Benutzer das Recht zur Verwendung des Semaphors verweigert, aber das Recht zum Lesen und Ändern des Semaphors gewährt. Wenn Sie das kompilierte Beispiel über zwei Befehlsfenster ausführen, löst die zweite Kopie beim Aufruf der OpenExisting(String) -Methode eine Zugriffsverletzungs-Ausnahme aus. Die Ausnahme wird abgefangen, und im Beispiel wird die OpenExisting(String, SemaphoreRights) Methodenüberladung verwendet, um den Semaphor mit den Zum Lesen und Ändern der Berechtigungen erforderlichen Rechten zu öffnen.

Nachdem die Berechtigungen geändert wurden, wird das Semaphor mit den zum Eingeben und Freigeben erforderlichen Rechten geöffnet. Wenn Sie das kompilierte Beispiel über ein drittes Befehlsfenster ausführen, wird es mit den neuen Berechtigungen ausgeführt.

#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

Hinweise

Verwenden Sie diesen Konstruktor, um die Zugriffssteuerungssicherheit auf einen benannten System-Semaphor anzuwenden, wenn es erstellt wird, wodurch verhindert wird, dass anderer Code die Kontrolle über das Semaphor übernimmt.

Kann name mit Global\ dem Präfix oder Local\ versehen werden, um einen Namespace anzugeben. Wenn der Global Namespace angegeben ist, kann das Synchronisierungsobjekt für alle Prozesse im System freigegeben werden. Wenn der Local Namespace angegeben wird, was auch der Standardwert ist, wenn kein Namespace angegeben wird, kann das Synchronisierungsobjekt für Prozesse in derselben Sitzung freigegeben werden. Unter Windows ist eine Sitzung eine Anmeldesitzung, und Dienste werden in der Regel in einer anderen nicht interaktiven Sitzung ausgeführt. Unter Unix-ähnlichen Betriebssystemen verfügt jede Shell über eine eigene Sitzung. Sitzungslokale Synchronisierungsobjekte eignen sich möglicherweise für die Synchronisierung zwischen Prozessen mit einer übergeordneten/untergeordneten Beziehung, bei der sie alle in derselben Sitzung ausgeführt werden. Weitere Informationen zu Synchronisierungsobjektnamen unter Windows finden Sie unter Objektnamen.

Wenn ein name bereitgestellt wird und bereits ein Synchronisierungsobjekt des angeforderten Typs im Namespace vorhanden ist, wird das vorhandene Synchronisierungsobjekt verwendet. Wenn im Namespace bereits ein Synchronisierungsobjekt eines anderen Typs vorhanden ist, wird ein WaitHandleCannotBeOpenedException ausgelöst. Andernfalls wird ein neues Synchronisierungsobjekt erstellt.

Dieser Konstruktor initialisiert ein Semaphore -Objekt, das einen benannten System-Semaphor darstellt. Sie können mehrere Semaphore Objekte erstellen, die denselben benannten System-Semaphor darstellen.

Wenn das benannte System-Semaphor nicht vorhanden ist, wird es mit der angegebenen Zugriffssteuerungssicherheit erstellt. Wenn das benannte Semaphor vorhanden ist, wird die angegebene Zugriffssteuerungssicherheit ignoriert.

Hinweis

Der Aufrufer hat die volle Kontrolle über das neu erstellte Semaphore Objekt, auch wenn semaphoreSecurity dem aktuellen Benutzer einige Zugriffsrechte verweigert oder nicht erteilt werden. Wenn der aktuelle Benutzer jedoch versucht, ein anderes Semaphore Objekt abzurufen, um dasselbe Semaphor darzustellen, indem er entweder einen Konstruktor oder die -Methode verwendet, wird die OpenExisting Windows-Zugriffssteuerungssicherheit angewendet.

Wenn der benannte System-Semaphor nicht vorhanden ist, wird es mit der anfänglichen Anzahl und der maximalen Anzahl erstellt, die von und maximumCountangegeben wirdinitialCount. Wenn der benannte System-Semaphor bereits vorhanden initialCount ist und maximumCount nicht verwendet wird, obwohl ungültige Werte weiterhin Ausnahmen verursachen. Verwenden Sie den createdNew -Parameter, um zu bestimmen, ob der System-Semaphor von diesem Konstruktor erstellt wurde.

Wenn initialCount kleiner als maximumCountist und createdNew ist, ist trueder Effekt identisch, als hätte der aktuelle Thread (maximumCountminus initialCount) mal aufgerufen WaitOne .

Wenn Sie oder eine leere Zeichenfolge für nameangebennull, wird ein lokaler Semaphor erstellt, als hätten Sie die Semaphore(Int32, Int32) Konstruktorüberladung aufgerufen. In diesem Fall createdNew ist immer true.

Da benannte Semaphore im gesamten Betriebssystem sichtbar sind, können sie verwendet werden, um die Ressourcennutzung über Prozessgrenzen hinweg zu koordinieren.

Achtung

Standardmäßig ist ein benannter Semaphor nicht auf den Benutzer beschränkt, der es erstellt hat. Andere Benutzer können das Semaphor möglicherweise öffnen und verwenden, einschließlich der Störung des Semaphors, indem sie das Semaphor mehrmals erwerben und nicht freigeben. Um den Zugriff auf bestimmte Benutzer einzuschränken, können Sie beim Erstellen des benannten Semaphors einen SemaphoreSecurity übergeben. Vermeiden Sie die Verwendung benannter Semaphore ohne Zugriffsbeschränkungen auf Systemen, auf denen möglicherweise nicht vertrauenswürdige Benutzer Code ausführen.

Weitere Informationen

Gilt für: