Semaphore Costruttori

Definizione

Inizializza una nuova istanza della classe Semaphore.

Overload

Semaphore(Int32, Int32)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di voci iniziale e il numero massimo di voci contemporanei.

Semaphore(Int32, Int32, String)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di accessi iniziale e il numero massimo di accessi contemporanei, nonché indicando facoltativamente il nome di un oggetto semaforo di sistema.

Semaphore(Int32, Int32, String, Boolean)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di accessi iniziale e il numero massimo di accessi contemporanei, indicando facoltativamente il nome di un oggetto semaforo di sistema e specificando una variabile che riceve un valore che indica se è stato creato un nuovo semaforo di sistema.

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

Inizializza una nuova istanza della classe Semaphore, specificando il numero iniziale di accessi e il numero massimo di accessi contemporanei, indicando facoltativamente il nome di un oggetto semaforo di sistema, specificando una variabile che riceve un valore che indica se è stato creato un nuovo semaforo di sistema e specificando la sicurezza del controllo di accesso per il semaforo di sistema.

Semaphore(Int32, Int32)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di voci iniziale e il numero massimo di voci contemporanei.

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)

Parametri

initialCount
Int32

Numero iniziale di richieste per il semaforo che possono essere concesse simultaneamente.

maximumCount
Int32

Numero massimo di richieste per il semaforo che possono essere concesse simultaneamente.

Eccezioni

initialCount è maggiore di maximumCount.

maximumCount è minore di 1.

-oppure-

initialCount è minore di 0.

Esempio

Nell'esempio seguente viene creato un semaforo con un numero massimo di tre e un conteggio iniziale di zero. L'esempio avvia cinque thread, che bloccano l'attesa del semaforo. Il thread principale usa l'overload del Release(Int32) metodo per aumentare il conteggio dei semafori al massimo, consentendo a tre thread di immettere il semaforo. Ogni thread usa il Thread.Sleep metodo per attendere un secondo, per simulare il lavoro e quindi chiama l'overload del metodo per rilasciare il Release() semaforo. Ogni volta che viene rilasciato il semaforo, viene visualizzato il conteggio del semaforo precedente. I messaggi della console tengono traccia dell'uso del semaforo. L'intervallo di lavoro simulato è aumentato leggermente per ogni thread, per semplificare la lettura dell'output.

#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

Commenti

Questo costruttore inizializza un semaforo senza nome. Tutti i thread che usano un'istanza di tale semaforo devono avere riferimenti all'istanza.

Se initialCount è minore di maximumCount, l'effetto è uguale a se il thread corrente aveva chiamato WaitOne (maximumCount meno initialCount) volte. Se non si desidera riservare voci per il thread che crea il semaforo, usare lo stesso numero per maximumCount e initialCount.

Vedi anche

Si applica a

Semaphore(Int32, Int32, String)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di accessi iniziale e il numero massimo di accessi contemporanei, nonché indicando facoltativamente il nome di un oggetto semaforo di sistema.

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)

Parametri

initialCount
Int32

Numero iniziale di richieste per il semaforo che possono essere concesse simultaneamente.

maximumCount
Int32

Numero massimo di richieste per il semaforo che possono essere concesse simultaneamente.

name
String

Il nome, se l'oggetto di sincronizzazione deve essere condiviso con altri processi; in caso contrario null o una stringa vuota. Per il nome è prevista la distinzione tra maiuscole e minuscole. Il carattere della barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.

Eccezioni

initialCount è maggiore di maximumCount.

-oppure-

Solo .NET Framework: la lunghezza di name supera MAX_PATH (260 caratteri).

maximumCount è minore di 1.

-oppure-

initialCount è minore di 0.

name non è valido. I motivi possono essere diversi, e tra questi limitazioni implementate dal sistema operativo, come prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" sono distinzione tra maiuscole e minuscole.

-oppure-

Si è verificato un altro errore. È possibile che la proprietà HResult offra ulteriori informazioni.

Solo Windows: name ha specificato uno spazio dei nomi sconosciuto. Per altre informazioni, vedere Object Names (Nomi oggetti).

name supera la lunghezza consentita. Le limitazioni di lunghezza possono dipendere dal sistema operativo o dalla configurazione.

Il semaforo denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.

Non è possibile creare un oggetto di sincronizzazione con l'elemento name specificato. Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome.

Esempio

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un semaforo denominato. Nell'esempio viene creato un semaforo denominato con un numero massimo di cinque e un conteggio iniziale di cinque. Il programma effettua tre chiamate al WaitOne metodo. Pertanto, se si esegue l'esempio compilato da due finestre di comando, la seconda copia verrà bloccata nella terza chiamata a WaitOne. Rilasciare una o più voci nella prima copia del programma per sbloccare il secondo.

#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

Commenti

Questo costruttore inizializza un oggetto che rappresenta un Semaphore semaforo di sistema denominato. È possibile creare più Semaphore oggetti che rappresentano lo stesso semaforo di sistema denominato.

Può name essere preceduto da Global\ o Local\ per specificare uno spazio dei nomi. Quando viene specificato lo spazio dei nomi, l'oggetto Global di sincronizzazione può essere condiviso con tutti i processi nel sistema. Quando viene specificato lo Local spazio dei nomi, che è anche il valore predefinito quando non viene specificato alcun spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi Unix, ogni shell ha la propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomi oggetti.

Se viene specificato un oggetto e un name oggetto di sincronizzazione del tipo richiesto esiste già nello spazio dei nomi, viene usato l'oggetto di sincronizzazione esistente. Se esiste già un oggetto di sincronizzazione di un tipo diverso nello spazio dei nomi, viene generato un WaitHandleCannotBeOpenedException oggetto di sincronizzazione. In caso contrario, viene creato un nuovo oggetto di sincronizzazione.

Se il semaforo di sistema denominato non esiste, viene creato con il conteggio iniziale e il numero massimo specificato da initialCount e maximumCount. Se il semaforo di sistema denominato esiste initialCount già e maximumCount non viene usato, anche se i valori non validi causano ancora eccezioni. Se è necessario determinare se è stato creato o meno un semaforo di sistema denominato, usare invece l'overload del Semaphore(Int32, Int32, String, Boolean) costruttore.

Importante

Quando si usa questo overload del costruttore, la procedura consigliata consiste nel specificare lo stesso numero per initialCount e maximumCount. Se initialCount è minore di maximumCounte viene creato un semaforo di sistema denominato, l'effetto è uguale a se il thread corrente aveva chiamato WaitOne (maximumCount meno initialCount) volte. Tuttavia, con questo overload del costruttore non è possibile determinare se è stato creato un semaforo di sistema denominato.

Se si specifica null o una stringa vuota per name, viene creato un semaforo locale, come se fosse stato chiamato l'overload del Semaphore(Int32, Int32) costruttore.

Poiché i semafori denominati sono visibili in tutto il sistema operativo, possono essere usati per coordinare l'uso delle risorse tra limiti di processo.

Se si vuole scoprire se esiste un semaforo di sistema denominato, usare il OpenExisting metodo . Il OpenExisting metodo tenta di aprire un semaforo denominato esistente e genera un'eccezione se il semaforo di sistema non esiste.

Attenzione

Per impostazione predefinita, un semaforo denominato non è limitato all'utente che lo ha creato. Altri utenti possono essere in grado di aprire e usare il semaforo, incluso l'interferimento con il semaforo acquisiscendo più volte il semaforo e non rilasciandolo. Per limitare l'accesso a utenti specifici, è possibile usare un overload del costruttore o SemaphoreAcl passare un SemaphoreSecurity oggetto durante la creazione del semaforo denominato. Evitare l'uso di semafori denominati senza restrizioni di accesso nei sistemi che potrebbero avere utenti non attendibili che eseguono codice.

Vedi anche

Si applica a

Semaphore(Int32, Int32, String, Boolean)

Inizializza una nuova istanza della classe Semaphore, specificando il numero di accessi iniziale e il numero massimo di accessi contemporanei, indicando facoltativamente il nome di un oggetto semaforo di sistema e specificando una variabile che riceve un valore che indica se è stato creato un nuovo semaforo di sistema.

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)

Parametri

initialCount
Int32

Numero iniziale di richieste per il semaforo che possono essere soddisfatte contemporaneamente.

maximumCount
Int32

Numero massimo di richieste per il semaforo che possono essere soddisfatte contemporaneamente.

name
String

Il nome, se l'oggetto di sincronizzazione deve essere condiviso con altri processi; in caso contrario null o una stringa vuota. Per il nome è prevista la distinzione tra maiuscole e minuscole. Il carattere della barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.

createdNew
Boolean

Quando questo metodo viene restituito, contiene true se è stato creato un semaforo locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato il semaforo di sistema denominato specificato; false se il semaforo di sistema denominato specificato è già esistente. Questo parametro viene passato non inizializzato.

Eccezioni

initialCount è maggiore di maximumCount.

-oppure-

Solo .NET Framework: la lunghezza di name supera MAX_PATH (260 caratteri).

maximumCount è minore di 1.

-oppure-

initialCount è minore di 0.

name non è valido. I motivi possono essere diversi, e tra questi limitazioni implementate dal sistema operativo, come prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" sono distinzione tra maiuscole e minuscole.

-oppure-

Si è verificato un altro errore. È possibile che la proprietà HResult offra ulteriori informazioni.

Solo Windows: name ha specificato uno spazio dei nomi sconosciuto. Per altre informazioni, vedere Object Names (Nomi oggetti).

name supera la lunghezza consentita. Le limitazioni di lunghezza possono dipendere dal sistema operativo o dalla configurazione.

Il semaforo denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.

Non è possibile creare un oggetto di sincronizzazione con l'elemento name specificato. Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome.

Esempio

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un semaforo denominato. L'esempio crea un semaforo denominato con un numero massimo di cinque e un conteggio iniziale di due. Vale a dire, riserva tre voci per il thread che chiama il costruttore. Se createNew è false, il programma effettua tre chiamate al WaitOne metodo. Pertanto, se si esegue l'esempio compilato da due finestre di comando, la seconda copia verrà bloccata nella terza chiamata a WaitOne. Rilasciare una o più voci nella prima copia del programma per sbloccare il secondo.

#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

Commenti

Può name essere preceduto da Global\ o Local\ per specificare uno spazio dei nomi. Quando viene specificato lo spazio dei nomi, l'oggetto Global di sincronizzazione può essere condiviso con tutti i processi nel sistema. Quando viene specificato lo Local spazio dei nomi, che è anche il valore predefinito quando non viene specificato alcun spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi Unix, ogni shell ha la propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomi oggetti.

Se viene specificato un oggetto e un name oggetto di sincronizzazione del tipo richiesto esiste già nello spazio dei nomi, viene usato l'oggetto di sincronizzazione esistente. Se esiste già un oggetto di sincronizzazione di un tipo diverso nello spazio dei nomi, viene generato un WaitHandleCannotBeOpenedException oggetto di sincronizzazione. In caso contrario, viene creato un nuovo oggetto di sincronizzazione.

Questo costruttore inizializza un oggetto che rappresenta un Semaphore semaforo di sistema denominato. È possibile creare più Semaphore oggetti che rappresentano lo stesso semaforo di sistema denominato.

Se il semaforo di sistema denominato non esiste, viene creato con il conteggio iniziale e il numero massimo specificato da initialCount e maximumCount. Se il semaforo di sistema denominato esiste initialCount già e maximumCount non viene usato, anche se i valori non validi causano ancora eccezioni. Usare createdNew per determinare se è stato creato il semaforo di sistema.

Se initialCount è minore di maximumCount, e createdNew è true, l'effetto è uguale a se il thread corrente aveva chiamato WaitOne (maximumCount meno initialCount) volte.

Se si specifica null o una stringa vuota per name, viene creato un semaforo locale, come se fosse stato chiamato l'overload del Semaphore(Int32, Int32) costruttore. In questo caso, createdNew è sempre true.

Poiché i semafori denominati sono visibili in tutto il sistema operativo, possono essere usati per coordinare l'uso delle risorse tra limiti di processo.

Attenzione

Per impostazione predefinita, un semaforo denominato non è limitato all'utente che lo ha creato. Altri utenti possono essere in grado di aprire e usare il semaforo, incluso l'interferimento con il semaforo acquisiscendo più volte il semaforo e non rilasciandolo. Per limitare l'accesso a utenti specifici, è possibile usare un overload del costruttore o SemaphoreAcl passare un SemaphoreSecurity oggetto durante la creazione del semaforo denominato. Evitare l'uso di semafori denominati senza restrizioni di accesso nei sistemi che potrebbero avere utenti non attendibili che eseguono codice.

Vedi anche

Si applica a

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

Inizializza una nuova istanza della classe Semaphore, specificando il numero iniziale di accessi e il numero massimo di accessi contemporanei, indicando facoltativamente il nome di un oggetto semaforo di sistema, specificando una variabile che riceve un valore che indica se è stato creato un nuovo semaforo di sistema e specificando la sicurezza del controllo di accesso per il semaforo di sistema.

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)

Parametri

initialCount
Int32

Numero iniziale di richieste per il semaforo che possono essere soddisfatte contemporaneamente.

maximumCount
Int32

Numero massimo di richieste per il semaforo che possono essere soddisfatte contemporaneamente.

name
String

Il nome, se l'oggetto di sincronizzazione deve essere condiviso con altri processi; in caso contrario null o una stringa vuota. Per il nome è prevista la distinzione tra maiuscole e minuscole. Il carattere della barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.

createdNew
Boolean

Quando questo metodo viene restituito, contiene true se è stato creato un semaforo locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato il semaforo di sistema denominato specificato; false se il semaforo di sistema denominato specificato è già esistente. Questo parametro viene passato non inizializzato.

semaphoreSecurity
SemaphoreSecurity

Oggetto SemaphoreSecurity che rappresenta la sicurezza del controllo di accesso da applicare al semaforo di sistema denominato.

Eccezioni

initialCount è maggiore di maximumCount.

-oppure-

Solo .NET Framework: la lunghezza di name supera MAX_PATH (260 caratteri).

maximumCount è minore di 1.

-oppure-

initialCount è minore di 0.

Il semaforo denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.

name non è valido. I motivi possono essere diversi, e tra questi limitazioni implementate dal sistema operativo, come prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" sono distinzione tra maiuscole e minuscole.

-oppure-

Si è verificato un altro errore. È possibile che la proprietà HResult offra ulteriori informazioni.

Solo Windows: name ha specificato uno spazio dei nomi sconosciuto. Per altre informazioni, vedere Object Names (Nomi oggetti).

name supera la lunghezza consentita. Le limitazioni di lunghezza possono dipendere dal sistema operativo o dalla configurazione.

Non è possibile creare un oggetto di sincronizzazione con l'elemento name specificato. Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome.

Esempio

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un semaforo denominato con sicurezza del controllo di accesso. Nell'esempio viene usato l'overload del OpenExisting(String) metodo per testare l'esistenza di un semaforo denominato. Se il semaforo non esiste, viene creato con un numero massimo di due e con la sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare il semaforo, ma concede il diritto di leggere e modificare le autorizzazioni per il semaforo. Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella chiamata al OpenExisting(String) metodo. L'eccezione viene rilevata e l'esempio usa l'overload del metodo per aprire il OpenExisting(String, SemaphoreRights) semaforo con i diritti necessari per leggere e modificare le autorizzazioni.

Dopo aver modificato le autorizzazioni, il semaforo viene aperto con i diritti necessari per immettere e rilasciare. Se si esegue l'esempio compilato da una terza finestra di comando, viene eseguito usando le nuove autorizzazioni.

#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

Commenti

Usare questo costruttore per applicare la sicurezza del controllo di accesso a un semaforo di sistema denominato quando viene creato, impedendo ad altri codici di controllare il semaforo.

Può name essere preceduto da Global\ o Local\ per specificare uno spazio dei nomi. Quando viene specificato lo spazio dei nomi, l'oggetto Global di sincronizzazione può essere condiviso con tutti i processi nel sistema. Quando viene specificato lo Local spazio dei nomi, che è anche il valore predefinito quando non viene specificato alcun spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi Unix, ogni shell ha la propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomi oggetti.

Se viene specificato un oggetto e un name oggetto di sincronizzazione del tipo richiesto esiste già nello spazio dei nomi, viene usato l'oggetto di sincronizzazione esistente. Se esiste già un oggetto di sincronizzazione di un tipo diverso nello spazio dei nomi, viene generato un WaitHandleCannotBeOpenedException oggetto di sincronizzazione. In caso contrario, viene creato un nuovo oggetto di sincronizzazione.

Questo costruttore inizializza un oggetto che rappresenta un Semaphore semaforo di sistema denominato. È possibile creare più Semaphore oggetti che rappresentano lo stesso semaforo di sistema denominato.

Se il semaforo di sistema denominato non esiste, viene creato con la sicurezza del controllo di accesso specificata. Se esiste il semaforo denominato, la sicurezza del controllo di accesso specificata viene ignorata.

Nota

Il chiamante ha il controllo completo sull'oggetto appena creato Semaphore anche se semaphoreSecurity nega o non concede alcuni diritti di accesso all'utente corrente. Tuttavia, se l'utente corrente tenta di ottenere un altro oggetto per rappresentare lo stesso semaforo denominato, usando un Semaphore costruttore o il metodo, viene applicata la sicurezza del OpenExisting controllo di accesso di Windows.

Se il semaforo di sistema denominato non esiste, viene creato con il conteggio iniziale e il numero massimo specificato da initialCount e maximumCount. Se il semaforo di sistema denominato esiste initialCount già e maximumCount non viene usato, anche se i valori non validi causano ancora eccezioni. Usare il createdNew parametro per determinare se il semaforo di sistema è stato creato da questo costruttore.

Se initialCount è minore di maximumCount, e createdNew è true, l'effetto è uguale a se il thread corrente aveva chiamato WaitOne (maximumCount meno initialCount) volte.

Se si specifica null o una stringa vuota per name, viene creato un semaforo locale, come se fosse stato chiamato l'overload del Semaphore(Int32, Int32) costruttore. In questo caso, createdNew è sempre true.

Poiché i semafori denominati sono visibili in tutto il sistema operativo, possono essere usati per coordinare l'uso delle risorse tra limiti di processo.

Attenzione

Per impostazione predefinita, un semaforo denominato non è limitato all'utente che lo ha creato. Altri utenti possono essere in grado di aprire e usare il semaforo, incluso l'interferimento con il semaforo acquisiscendo più volte il semaforo e non rilasciandolo. Per limitare l'accesso a utenti specifici, è possibile passare un SemaphoreSecurity oggetto durante la creazione del semaforo denominato. Evitare l'uso di semafori denominati senza restrizioni di accesso nei sistemi che potrebbero avere utenti non attendibili che eseguono codice.

Vedi anche

Si applica a