Semaphore Construtores

Definição

Inicializa uma nova instância da classe Semaphore.

Sobrecargas

Semaphore(Int32, Int32)

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas.

Semaphore(Int32, Int32, String)

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas e, opcionalmente, especificando o nome de um objeto de sinal de sistema.

Semaphore(Int32, Int32, String, Boolean)

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas, opcionalmente especificando o nome de um objeto de semáforo de sistema e especificando uma variável que recebe um valor que indica se um novo semáforo do sistema foi criado.

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

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas, opcionalmente especificando o nome de um objeto de semáforo de sistema, especificando uma variável que recebe um valor que indica se um novo semáforo do sistema foi criado e especificando o controle de acesso de segurança para o semáforo do sistema.

Semaphore(Int32, Int32)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas.

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)

Parâmetros

initialCount
Int32

O número inicial de solicitações para o semáforo que podem ser concedidas ao mesmo tempo.

maximumCount
Int32

O número máximo de solicitações para o semáforo que podem ser concedidas ao mesmo tempo.

Exceções

initialCount é maior que maximumCount.

maximumCount é menor que 1.

- ou -

initialCount é menor que 0.

Exemplos

O exemplo a seguir cria um semáforo com uma contagem máxima de três e uma contagem inicial de zero. O exemplo inicia cinco threads, que bloqueiam a espera pelo semáforo. O thread main usa a sobrecarga do Release(Int32) método para aumentar a contagem de semáforos para o máximo, permitindo que três threads insiram o semáforo. Cada thread usa o Thread.Sleep método para aguardar um segundo, para simular o trabalho e, em seguida, chama a sobrecarga do Release() método para liberar o semáforo. Cada vez que o semáforo é liberado, a contagem de semáforos anterior é exibida. As mensagens do console rastreiam o uso do semáforo. O intervalo de trabalho simulado é ligeiramente aumentado para cada thread, para facilitar a leitura da saída.

#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

Comentários

Esse construtor inicializa um semáforo sem nome. Todos os threads que usam uma instância desse semáforo devem ter referências à instância .

Se initialCount for menor que maximumCount, o efeito será o mesmo que se o thread atual tivesse chamado WaitOne (maximumCount menos initialCount) vezes. Se você não quiser reservar nenhuma entrada para o thread que cria o semáforo, use o mesmo número para maximumCount e initialCount.

Confira também

Aplica-se a

Semaphore(Int32, Int32, String)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas e, opcionalmente, especificando o nome de um objeto de sinal de 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)

Parâmetros

initialCount
Int32

O número inicial de solicitações para o semáforo que podem ser concedidas ao mesmo tempo.

maximumCount
Int32

O número máximo de solicitações para o semáforo que podem ser concedidas ao mesmo tempo.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

Exceções

initialCount é maior que maximumCount.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

maximumCount é menor que 1.

- ou -

initialCount é menor que 0.

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

O sinal nomeado existe e tem segurança de controle de acesso e o usuário não tem FullControl.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

Exemplos

O exemplo de código a seguir demonstra o comportamento entre processos de um semáforo nomeado. O exemplo cria um semáforo nomeado com uma contagem máxima de cinco e uma contagem inicial de cinco. O programa faz três chamadas para o WaitOne método . Portanto, se você executar o exemplo compilado de duas janelas de comando, a segunda cópia será bloqueada na terceira chamada para WaitOne. Libere uma ou mais entradas na primeira cópia do programa para desbloquear a segunda.

#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

Comentários

Esse construtor inicializa um Semaphore objeto que representa um semáforo do sistema nomeado. Você pode criar vários Semaphore objetos que representam o mesmo semáforo do sistema nomeado.

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será usado. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Se o semáforo do sistema nomeado não existir, ele será criado com a contagem inicial e a contagem máxima especificadas por initialCount e maximumCount. Se o semáforo do sistema nomeado já existir initialCount e maximumCount não for usado, embora valores inválidos ainda causem exceções. Se você precisar determinar se um semáforo de sistema nomeado foi ou não criado, use a sobrecarga do Semaphore(Int32, Int32, String, Boolean) construtor.

Importante

Quando você usa essa sobrecarga de construtor, a prática recomendada é especificar o mesmo número para initialCount e maximumCount. Se initialCount for menor que maximumCounte um semáforo de sistema nomeado for criado, o efeito será o mesmo que se o thread atual tivesse chamado WaitOne (maximumCount menos initialCount) vezes. No entanto, com essa sobrecarga de construtor, não há como determinar se um semáforo de sistema nomeado foi criado.

Se você especificar null ou uma cadeia de caracteres vazia para name, um semáforo local será criado, como se você tivesse chamado a sobrecarga do Semaphore(Int32, Int32) construtor.

Como os semáforos nomeados são visíveis em todo o sistema operacional, eles podem ser usados para coordenar o uso de recursos entre limites do processo.

Se você quiser descobrir se existe um semáforo de sistema nomeado, use o OpenExisting método . O OpenExisting método tenta abrir um semáforo nomeado existente e gera uma exceção se o semáforo do sistema não existir.

Cuidado

Por padrão, um semáforo nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o semáforo, incluindo interferir no semáforo adquirindo o semáforo várias vezes e não liberando-o. Para restringir o acesso a usuários específicos, você pode usar uma sobrecarga de construtor ou SemaphoreAcl e passar um SemaphoreSecurity ao criar o semáforo nomeado. Evite usar semáforos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Confira também

Aplica-se a

Semaphore(Int32, Int32, String, Boolean)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas, opcionalmente especificando o nome de um objeto de semáforo de sistema e especificando uma variável que recebe um valor que indica se um novo semáforo do sistema foi criado.

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)

Parâmetros

initialCount
Int32

O número inicial de solicitações para o semáforo que podem ser atendidas simultaneamente.

maximumCount
Int32

O número máximo de solicitações para o semáforo que podem ser atendidas simultaneamente.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

createdNew
Boolean

Quando este método retorna, ele conterá true, se um semáforo local tiver sido criado (isto é, se name for null ou uma cadeia de caracteres vazia) ou se o semáforo de sistema nomeado especificado tiver sido criado, false se o semáforo de sistema nomeado especificado já existia. Este parâmetro é passado não inicializado.

Exceções

initialCount é maior que maximumCount.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

maximumCount é menor que 1.

- ou -

initialCount é menor que 0.

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

O sinal nomeado existe e tem segurança de controle de acesso e o usuário não tem FullControl.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

Exemplos

O exemplo de código a seguir demonstra o comportamento entre processos de um semáforo nomeado. O exemplo cria um semáforo nomeado com uma contagem máxima de cinco e uma contagem inicial de dois. Ou seja, ele reserva três entradas para o thread que chama o construtor. Se createNew for false, o programa fará três chamadas para o WaitOne método . Portanto, se você executar o exemplo compilado de duas janelas de comando, a segunda cópia será bloqueada na terceira chamada para WaitOne. Libere uma ou mais entradas na primeira cópia do programa para desbloquear a segunda.

#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

Comentários

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será usado. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Esse construtor inicializa um Semaphore objeto que representa um semáforo do sistema nomeado. Você pode criar vários Semaphore objetos que representam o mesmo semáforo do sistema nomeado.

Se o semáforo do sistema nomeado não existir, ele será criado com a contagem inicial e a contagem máxima especificadas por initialCount e maximumCount. Se o semáforo do sistema nomeado já existir initialCount e maximumCount não for usado, embora valores inválidos ainda causem exceções. Use createdNew para determinar se o semáforo do sistema foi criado.

Se initialCount for menor que maximumCounte createdNew for true, o efeito será o mesmo que se o thread atual tivesse chamado WaitOne (maximumCount menos initialCount) vezes.

Se você especificar null ou uma cadeia de caracteres vazia para name, um semáforo local será criado, como se você tivesse chamado a sobrecarga do Semaphore(Int32, Int32) construtor. Nesse caso, createdNew é sempre true.

Como os semáforos nomeados são visíveis em todo o sistema operacional, eles podem ser usados para coordenar o uso de recursos entre limites do processo.

Cuidado

Por padrão, um semáforo nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o semáforo, incluindo interferir no semáforo adquirindo o semáforo várias vezes e não liberando-o. Para restringir o acesso a usuários específicos, você pode usar uma sobrecarga de construtor ou SemaphoreAcl e passar um SemaphoreSecurity ao criar o semáforo nomeado. Evite usar semáforos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Confira também

Aplica-se a

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

Inicializa uma nova instância da classe Semaphore, especificando o número inicial de entradas e o número máximo de entradas simultâneas, opcionalmente especificando o nome de um objeto de semáforo de sistema, especificando uma variável que recebe um valor que indica se um novo semáforo do sistema foi criado e especificando o controle de acesso de segurança para o semáforo do 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)

Parâmetros

initialCount
Int32

O número inicial de solicitações para o semáforo que podem ser atendidas simultaneamente.

maximumCount
Int32

O número máximo de solicitações para o semáforo que podem ser atendidas simultaneamente.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

createdNew
Boolean

Quando este método retorna, ele conterá true, se um semáforo local tiver sido criado (isto é, se name for null ou uma cadeia de caracteres vazia) ou se o semáforo de sistema nomeado especificado tiver sido criado, false se o semáforo de sistema nomeado especificado já existia. Este parâmetro é passado não inicializado.

semaphoreSecurity
SemaphoreSecurity

Um objeto SemaphoreSecurity que representa a segurança de controle de acesso a ser aplicada ao semáforo de sistema nomeado.

Exceções

initialCount é maior que maximumCount.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

maximumCount é menor que 1.

- ou -

initialCount é menor que 0.

O sinal nomeado existe e tem segurança de controle de acesso e o usuário não tem FullControl.

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

Exemplos

O exemplo de código a seguir demonstra o comportamento entre processos de um semáforo nomeado com segurança de controle de acesso. O exemplo usa a sobrecarga do OpenExisting(String) método para testar a existência de um semáforo nomeado. Se o semáforo não existir, ele será criado com uma contagem máxima de dois e com segurança de controle de acesso que nega ao usuário atual o direito de usar o semáforo, mas concede o direito de ler e alterar permissões no semáforo. Se você executar o exemplo compilado em duas janelas de comando, a segunda cópia gerará uma exceção de violação de acesso na chamada para o OpenExisting(String) método . A exceção é capturada e o exemplo usa a sobrecarga do OpenExisting(String, SemaphoreRights) método para abrir o semáforo com os direitos necessários para ler e alterar as permissões.

Depois que as permissões são alteradas, o semáforo é aberto com os direitos necessários para inserir e liberar. Se você executar o exemplo compilado de uma terceira janela de comando, ele será executado usando as novas permissões.

#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

Comentários

Use esse construtor para aplicar a segurança de controle de acesso a um semáforo do sistema nomeado quando ele for criado, impedindo que outro código assumisse o controle do semáforo.

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será usado. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Esse construtor inicializa um Semaphore objeto que representa um semáforo do sistema nomeado. Você pode criar vários Semaphore objetos que representam o mesmo semáforo do sistema nomeado.

Se o semáforo do sistema nomeado não existir, ele será criado com a segurança de controle de acesso especificada. Se o semáforo nomeado existir, a segurança de controle de acesso especificada será ignorada.

Observação

O chamador tem controle total sobre o objeto recém-criado Semaphore , mesmo que semaphoreSecurity negue ou não conceda alguns direitos de acesso ao usuário atual. No entanto, se o usuário atual tentar obter outro Semaphore objeto para representar o mesmo semáforo nomeado, usando um construtor ou o método , a segurança do controle de acesso do OpenExisting Windows será aplicada.

Se o semáforo do sistema nomeado não existir, ele será criado com a contagem inicial e a contagem máxima especificadas por initialCount e maximumCount. Se o semáforo do sistema nomeado já existir initialCount e maximumCount não for usado, embora valores inválidos ainda causem exceções. Use o createdNew parâmetro para determinar se o semáforo do sistema foi criado por esse construtor.

Se initialCount for menor que maximumCounte createdNew for true, o efeito será o mesmo que se o thread atual tivesse chamado WaitOne (maximumCount menos initialCount) vezes.

Se você especificar null ou uma cadeia de caracteres vazia para name, um semáforo local será criado, como se você tivesse chamado a sobrecarga do Semaphore(Int32, Int32) construtor. Nesse caso, createdNew é sempre true.

Como os semáforos nomeados são visíveis em todo o sistema operacional, eles podem ser usados para coordenar o uso de recursos entre limites do processo.

Cuidado

Por padrão, um semáforo nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o semáforo, incluindo interferir no semáforo adquirindo o semáforo várias vezes e não liberando-o. Para restringir o acesso a usuários específicos, você pode passar um SemaphoreSecurity ao criar o semáforo nomeado. Evite usar semáforos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Confira também

Aplica-se a