Semaphore Constructores

Definición

Inicializa una nueva instancia de la clase Semaphore.

Sobrecargas

Semaphore(Int32, Int32)

Inicializa una nueva instancia de la clase Semaphore, que especifica el número inicial de entradas y el número máximo de entradas simultáneas.

Semaphore(Int32, Int32, String)

Inicializa una nueva instancia de la clase Semaphore, que especifica el número inicial de entradas y el número máximo de entradas simultáneas, y especificando de forma opcional el nombre de un objeto semáforo de sistema.

Semaphore(Int32, Int32, String, Boolean)

Inicializa una instancia nueva de la clase Semaphore, especificando el número inicial de entradas y el número máximo de entradas simultáneas, especificando de forma opcional el nombre de un objeto semáforo de sistema y especificando una variable que recibe un valor que indica si se creó un semáforo del sistema nuevo.

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

Inicializa una instancia nueva de la clase Semaphore, especificando el número inicial de entradas y el número máximo de entradas simultáneas, especificando de forma opcional el nombre de un objeto semáforo de sistema, especificando una variable que recibe un valor que indica si se creó un semáforo del sistema y especificando la seguridad de control de acceso para el semáforo del sistema.

Semaphore(Int32, Int32)

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

Inicializa una nueva instancia de la clase Semaphore, que especifica el número inicial de entradas y el 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

Número inicial de solicitudes del semáforo que se pueden conceder simultáneamente.

maximumCount
Int32

Número máximo de solicitudes del semáforo que se pueden conceder simultáneamente.

Excepciones

initialCount es mayor que maximumCount.

maximumCount es menor que 1.

O bien

initialCount es menor que 0.

Ejemplos

En el ejemplo siguiente se crea un semáforo con un recuento máximo de tres y un recuento inicial de cero. En el ejemplo se inician cinco subprocesos, que bloquean la espera del semáforo. El subproceso principal usa la sobrecarga del Release(Int32) método para aumentar el recuento de semáforos a su máximo, lo que permite que tres subprocesos entren en el semáforo. Cada subproceso usa el Thread.Sleep método para esperar un segundo, simular el trabajo y, a continuación, llama a la sobrecarga del Release() método para liberar el semáforo. Cada vez que se libera el semáforo, se muestra el recuento de semáforos anterior. Los mensajes de la consola realizan un seguimiento del uso del semáforo. El intervalo de trabajo simulado se incrementa ligeramente para cada subproceso, para facilitar la lectura de la salida.

#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

Comentarios

Este constructor inicializa un semáforo sin nombre. Todos los subprocesos que usan una instancia de este semáforo deben tener referencias a la instancia.

Si initialCount es menor que maximumCount, el efecto es el mismo que si el subproceso actual hubiera llamado WaitOne (maximumCount menos initialCount) veces. Si no desea reservar ninguna entrada para el subproceso que cree el semáforo, use el mismo número para maximumCount y initialCount.

Consulte también

Se aplica a

Semaphore(Int32, Int32, String)

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

Inicializa una nueva instancia de la clase Semaphore, que especifica el número inicial de entradas y el número máximo de entradas simultáneas, y especificando de forma opcional el nombre de un objeto semáforo 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

Número inicial de solicitudes del semáforo que se pueden conceder simultáneamente.

maximumCount
Int32

Número máximo de solicitudes del semáforo que se pueden conceder simultáneamente.

name
String

Nombre, si el objeto de sincronización se va a compartir con otros procesos; en caso contrario, null o una cadena vacía. El nombre distingue entre mayúsculas y minúsculas. El carácter de barra diagonal inversa (\) está reservado y solo se puede usar para especificar un espacio de nombres. Para obtener más información sobre los espacios de nombres, consulte la sección comentarios. Puede haber más restricciones en el nombre en función del sistema operativo. Por ejemplo, en los sistemas operativos basados en Unix, el nombre después de excluir el espacio de nombres debe ser un nombre de archivo válido.

Excepciones

initialCount es mayor que maximumCount.

O bien

Solo .NET Framework: name es mayor que MAX_PATH (260 caracteres).

maximumCount es menor que 1.

O bien

initialCount es menor que 0.

name no es válido. Esto puede deberse a diversos motivos, incluidas algunas restricciones que puede imponer el sistema operativo, como un prefijo desconocido o caracteres no válidos. Tenga en cuenta que el nombre y los prefijos comunes "Global\" y "Local\" distinguen mayúsculas de minúsculas.

O bien

Hubo algún otro error. La propiedad HResult puede proporcionar más información.

Solo Windows: name especificó un espacio de nombres desconocido. Consulte Nombres de objetos para obtener más información.

name es demasiado largo. Las restricciones de longitud pueden depender del sistema operativo o la configuración.

El semáforo con nombre existe y tiene seguridad de control de acceso, y el usuario no tiene FullControl.

No se puede crear un objeto de sincronización con el valor name proporcionado. Un objeto de sincronización de un tipo diferente podría tener el mismo nombre.

Ejemplos

En el ejemplo de código siguiente se muestra el comportamiento entre procesos de un semáforo con nombre. En el ejemplo se crea un semáforo con nombre con un recuento máximo de cinco y un recuento inicial de cinco. El programa realiza tres llamadas al WaitOne método . Por lo tanto, si ejecuta el ejemplo compilado desde dos ventanas de comandos, la segunda copia se bloqueará en la tercera llamada a WaitOne. Libere una o varias entradas en la primera copia del programa para desbloquear la 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

Comentarios

Este constructor inicializa un Semaphore objeto que representa un semáforo del sistema con nombre. Puede crear varios Semaphore objetos que representen el mismo semáforo del sistema con nombre.

name puede tener el prefijo o Global\Local\ especificar un espacio de nombres. Cuando se especifica el Global espacio de nombres, el objeto de sincronización se puede compartir con cualquier proceso del sistema. Cuando se especifica el Local espacio de nombres , que también es el valor predeterminado cuando no se especifica ningún espacio de nombres, el objeto de sincronización se puede compartir con procesos en la misma sesión. En Windows, una sesión es una sesión de inicio de sesión y los servicios normalmente se ejecutan en una sesión no interactiva diferente. En sistemas operativos similares a Unix, cada shell tiene su propia sesión. Los objetos de sincronización local de sesión pueden ser adecuados para sincronizar entre procesos con una relación primaria o secundaria en la que se ejecutan en la misma sesión. Para obtener más información sobre los nombres de objetos de sincronización en Windows, vea Nombres de objeto.

Si se proporciona y name ya existe un objeto de sincronización del tipo solicitado en el espacio de nombres, se usa el objeto de sincronización existente. Si ya existe un objeto de sincronización de un tipo diferente en el espacio de nombres , se produce una WaitHandleCannotBeOpenedException excepción . De lo contrario, se crea un nuevo objeto de sincronización.

Si el semáforo del sistema con nombre no existe, se crea con el recuento inicial y el recuento máximo especificados por initialCount y maximumCount. Si el semáforo del sistema con nombre ya existe initialCount y maximumCount no se usa, aunque los valores no válidos siguen causando excepciones. Si necesita determinar si se creó o no un semáforo del sistema con nombre, use la sobrecarga del Semaphore(Int32, Int32, String, Boolean) constructor en su lugar.

Importante

Cuando se usa esta sobrecarga de constructor, la práctica recomendada es especificar el mismo número para initialCount y maximumCount. Si initialCount es menor que maximumCounty se crea un semáforo del sistema con nombre, el efecto es el mismo que si el subproceso actual hubiera llamado WaitOne (maximumCount menos initialCount) veces. Sin embargo, con esta sobrecarga del constructor no hay ninguna manera de determinar si se creó un semáforo del sistema con nombre.

Si especifica null o una cadena vacía para name, se crea un semáforo local, como si hubiera llamado a la sobrecarga del Semaphore(Int32, Int32) constructor.

Dado que los semáforos con nombre son visibles en todo el sistema operativo, se pueden usar para coordinar el uso de recursos a través de los límites del proceso.

Si desea averiguar si existe un semáforo del sistema con nombre, use el OpenExisting método . El OpenExisting método intenta abrir un semáforo con nombre existente y produce una excepción si el semáforo del sistema no existe.

Precaución

De forma predeterminada, un semáforo con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el semáforo, incluida la interferencia con el semáforo al adquirir el semáforo varias veces y no liberarlo. Para restringir el acceso a usuarios específicos, puede usar una sobrecarga de constructor o SemaphoreAcl pasar un SemaphoreSecurity elemento al crear el semáforo con nombre. Evite usar semáforos con nombre sin restricciones de acceso en sistemas que podrían tener usuarios que no son de confianza ejecutando código.

Consulte también

Se aplica a

Semaphore(Int32, Int32, String, Boolean)

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

Inicializa una instancia nueva de la clase Semaphore, especificando el número inicial de entradas y el número máximo de entradas simultáneas, especificando de forma opcional el nombre de un objeto semáforo de sistema y especificando una variable que recibe un valor que indica si se creó un semáforo del sistema nuevo.

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

Número inicial de solicitudes para el semáforo que se puede satisfacer simultáneamente.

maximumCount
Int32

Número máximo de solicitudes para el semáforo que se puede satisfacer simultáneamente.

name
String

Nombre, si el objeto de sincronización se va a compartir con otros procesos; en caso contrario, null o una cadena vacía. El nombre distingue entre mayúsculas y minúsculas. El carácter de barra diagonal inversa (\) está reservado y solo se puede usar para especificar un espacio de nombres. Para obtener más información sobre los espacios de nombres, consulte la sección comentarios. Puede haber más restricciones en el nombre en función del sistema operativo. Por ejemplo, en los sistemas operativos basados en Unix, el nombre después de excluir el espacio de nombres debe ser un nombre de archivo válido.

createdNew
Boolean

Cuando este método devuelve un resultado, contiene true si se creó un semáforo local (es decir, si name es null o una cadena vacía) o si se creó el semáforo del sistema con nombre especificado; es false si el semáforo del sistema con nombre especificado ya existía. Este parámetro se pasa sin inicializar.

Excepciones

initialCount es mayor que maximumCount.

O bien

Solo .NET Framework: name es mayor que MAX_PATH (260 caracteres).

maximumCount es menor que 1.

O bien

initialCount es menor que 0.

name no es válido. Esto puede deberse a diversos motivos, incluidas algunas restricciones que puede imponer el sistema operativo, como un prefijo desconocido o caracteres no válidos. Tenga en cuenta que el nombre y los prefijos comunes "Global\" y "Local\" distinguen mayúsculas de minúsculas.

O bien

Hubo algún otro error. La propiedad HResult puede proporcionar más información.

Solo Windows: name especificó un espacio de nombres desconocido. Consulte Nombres de objetos para obtener más información.

name es demasiado largo. Las restricciones de longitud pueden depender del sistema operativo o la configuración.

El semáforo con nombre existe y tiene seguridad de control de acceso, y el usuario no tiene FullControl.

No se puede crear un objeto de sincronización con el valor name proporcionado. Un objeto de sincronización de un tipo diferente podría tener el mismo nombre.

Ejemplos

En el ejemplo de código siguiente se muestra el comportamiento entre procesos de un semáforo con nombre. En el ejemplo se crea un semáforo con nombre con un recuento máximo de cinco y un recuento inicial de dos. Es decir, reserva tres entradas para el subproceso que llama al constructor. Si createNew es false, el programa realiza tres llamadas al WaitOne método . Por lo tanto, si ejecuta el ejemplo compilado desde dos ventanas de comandos, la segunda copia se bloqueará en la tercera llamada a WaitOne. Libere una o varias entradas en la primera copia del programa para desbloquear la 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

Comentarios

name puede tener como prefijo Global\ o Local\ especificar un espacio de nombres. Cuando se especifica el Global espacio de nombres, el objeto de sincronización se puede compartir con cualquier proceso del sistema. Cuando se especifica el Local espacio de nombres , que también es el valor predeterminado cuando no se especifica ningún espacio de nombres, el objeto de sincronización se puede compartir con procesos en la misma sesión. En Windows, una sesión es una sesión de inicio de sesión y los servicios normalmente se ejecutan en una sesión no interactiva diferente. En sistemas operativos similares a Unix, cada shell tiene su propia sesión. Los objetos de sincronización local de sesión pueden ser adecuados para sincronizar entre procesos con una relación primaria o secundaria en la que se ejecutan todas en la misma sesión. Para obtener más información sobre los nombres de objetos de sincronización en Windows, vea Nombres de objeto.

Si se proporciona y name ya existe un objeto de sincronización del tipo solicitado en el espacio de nombres , se usa el objeto de sincronización existente. Si ya existe un objeto de sincronización de otro tipo en el espacio de nombres , se produce una WaitHandleCannotBeOpenedException excepción . De lo contrario, se crea un nuevo objeto de sincronización.

Este constructor inicializa un Semaphore objeto que representa un semáforo del sistema con nombre. Puede crear varios Semaphore objetos que representen el mismo semáforo del sistema con nombre.

Si el semáforo del sistema con nombre no existe, se crea con el recuento inicial y el recuento máximo especificados por initialCount y maximumCount. Si el semáforo del sistema con nombre ya existe initialCount y maximumCount no se usa, aunque los valores no válidos siguen provocando excepciones. Use createdNew para determinar si se creó el semáforo del sistema.

Si initialCount es menor que maximumCount, y createdNew es true, el efecto es el mismo que si el subproceso actual hubiera llamado ( WaitOnemaximumCount menos initialCount) veces.

Si especifica null o una cadena vacía para name, se crea un semáforo local, como si hubiera llamado a la sobrecarga del Semaphore(Int32, Int32) constructor. En este caso, createdNew siempre truees .

Dado que los semáforos con nombre son visibles en todo el sistema operativo, se pueden usar para coordinar el uso de recursos a través de los límites del proceso.

Precaución

De forma predeterminada, un semáforo con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el semáforo, incluida la interferencia con el semáforo al adquirir el semáforo varias veces y no liberarlo. Para restringir el acceso a usuarios específicos, puede usar una sobrecarga de constructor o SemaphoreAcl pasar un SemaphoreSecurity al crear el semáforo con nombre. Evite usar semáforos con nombre sin restricciones de acceso en sistemas que puedan tener usuarios que no son de confianza que ejecuten código.

Consulte también

Se aplica a

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

Inicializa una instancia nueva de la clase Semaphore, especificando el número inicial de entradas y el número máximo de entradas simultáneas, especificando de forma opcional el nombre de un objeto semáforo de sistema, especificando una variable que recibe un valor que indica si se creó un semáforo del sistema y especificando la seguridad de control de acceso para el semáforo del 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

Número inicial de solicitudes para el semáforo que se puede satisfacer simultáneamente.

maximumCount
Int32

Número máximo de solicitudes para el semáforo que se puede satisfacer simultáneamente.

name
String

Nombre, si el objeto de sincronización se va a compartir con otros procesos; en caso contrario, null o una cadena vacía. El nombre distingue entre mayúsculas y minúsculas. El carácter de barra diagonal inversa (\) está reservado y solo se puede usar para especificar un espacio de nombres. Para obtener más información sobre los espacios de nombres, consulte la sección comentarios. Puede haber más restricciones en el nombre en función del sistema operativo. Por ejemplo, en los sistemas operativos basados en Unix, el nombre después de excluir el espacio de nombres debe ser un nombre de archivo válido.

createdNew
Boolean

Cuando este método devuelve un resultado, contiene true si se creó un semáforo local (es decir, si name es null o una cadena vacía) o si se creó el semáforo del sistema con nombre especificado; es false si el semáforo del sistema con nombre especificado ya existía. Este parámetro se pasa sin inicializar.

semaphoreSecurity
SemaphoreSecurity

Objeto SemaphoreSecurity que representa la seguridad de control de acceso que se aplicará al semáforo de sistema con nombre.

Excepciones

initialCount es mayor que maximumCount.

O bien

Solo .NET Framework: name es mayor que MAX_PATH (260 caracteres).

maximumCount es menor que 1.

O bien

initialCount es menor que 0.

El semáforo con nombre existe y tiene seguridad de control de acceso, y el usuario no tiene FullControl.

name no es válido. Esto puede deberse a diversos motivos, incluidas algunas restricciones que puede imponer el sistema operativo, como un prefijo desconocido o caracteres no válidos. Tenga en cuenta que el nombre y los prefijos comunes "Global\" y "Local\" distinguen mayúsculas de minúsculas.

O bien

Hubo algún otro error. La propiedad HResult puede proporcionar más información.

Solo Windows: name especificó un espacio de nombres desconocido. Consulte Nombres de objetos para obtener más información.

name es demasiado largo. Las restricciones de longitud pueden depender del sistema operativo o la configuración.

No se puede crear un objeto de sincronización con el valor name proporcionado. Un objeto de sincronización de un tipo diferente podría tener el mismo nombre.

Ejemplos

En el ejemplo de código siguiente se muestra el comportamiento entre procesos de un semáforo con nombre con seguridad de control de acceso. En el ejemplo se usa la sobrecarga del OpenExisting(String) método para probar la existencia de un semáforo con nombre. Si el semáforo no existe, se crea con un recuento máximo de dos y con seguridad de control de acceso que deniega al usuario actual el derecho de usar el semáforo, pero concede el derecho de lectura y cambio de permisos en el semáforo. Si ejecuta el ejemplo compilado desde dos ventanas de comandos, la segunda copia producirá una excepción de infracción de acceso en la llamada al OpenExisting(String) método . La excepción se detecta y el ejemplo usa la OpenExisting(String, SemaphoreRights) sobrecarga del método para abrir el semáforo con los derechos necesarios para leer y cambiar los permisos.

Una vez cambiados los permisos, el semáforo se abre con los derechos necesarios para entrar y liberar. Si ejecuta el ejemplo compilado desde una tercera ventana de comandos, se ejecuta con los nuevos permisos.

#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

Comentarios

Use este constructor para aplicar la seguridad del control de acceso a un semáforo del sistema con nombre cuando se crea, lo que impide que otro código controle el semáforo.

name puede tener como prefijo Global\ o Local\ especificar un espacio de nombres. Cuando se especifica el Global espacio de nombres, el objeto de sincronización se puede compartir con cualquier proceso del sistema. Cuando se especifica el Local espacio de nombres , que también es el valor predeterminado cuando no se especifica ningún espacio de nombres, el objeto de sincronización se puede compartir con procesos en la misma sesión. En Windows, una sesión es una sesión de inicio de sesión y los servicios normalmente se ejecutan en una sesión no interactiva diferente. En sistemas operativos similares a Unix, cada shell tiene su propia sesión. Los objetos de sincronización local de sesión pueden ser adecuados para sincronizar entre procesos con una relación primaria o secundaria en la que se ejecutan en la misma sesión. Para obtener más información sobre los nombres de objetos de sincronización en Windows, vea Nombres de objeto.

Si se proporciona y name ya existe un objeto de sincronización del tipo solicitado en el espacio de nombres, se usa el objeto de sincronización existente. Si ya existe un objeto de sincronización de un tipo diferente en el espacio de nombres , se produce una WaitHandleCannotBeOpenedException excepción . De lo contrario, se crea un nuevo objeto de sincronización.

Este constructor inicializa un Semaphore objeto que representa un semáforo del sistema con nombre. Puede crear varios Semaphore objetos que representen el mismo semáforo del sistema con nombre.

Si el semáforo del sistema con nombre no existe, se crea con la seguridad de control de acceso especificada. Si existe el semáforo con nombre, se omite la seguridad del control de acceso especificada.

Nota:

El autor de la llamada tiene control total sobre el objeto recién creado Semaphore aunque semaphoreSecurity deniega o no conceda derechos de acceso al usuario actual. Sin embargo, si el usuario actual intenta obtener otro Semaphore objeto para representar el mismo semáforo con nombre, mediante un constructor o el OpenExisting método , se aplica la seguridad del control de acceso de Windows.

Si el semáforo del sistema con nombre no existe, se crea con el recuento inicial y el recuento máximo especificados por initialCount y maximumCount. Si el semáforo del sistema con nombre ya existe initialCount y maximumCount no se usa, aunque los valores no válidos siguen causando excepciones. Use el createdNew parámetro para determinar si este constructor creó el semáforo del sistema.

Si initialCount es menor que maximumCount, y createdNew es true, el efecto es el mismo que si el subproceso actual hubiera llamado WaitOne (maximumCount menos initialCount) veces.

Si especifica null o una cadena vacía para name, se crea un semáforo local, como si hubiera llamado a la sobrecarga del Semaphore(Int32, Int32) constructor. En este caso, createdNew siempre truees .

Dado que los semáforos con nombre son visibles en todo el sistema operativo, se pueden usar para coordinar el uso de recursos a través de los límites del proceso.

Precaución

De forma predeterminada, un semáforo con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el semáforo, incluida la interferencia con el semáforo al adquirir el semáforo varias veces y no liberarlo. Para restringir el acceso a usuarios específicos, puede pasar un SemaphoreSecurity elemento al crear el semáforo con nombre. Evite usar semáforos con nombre sin restricciones de acceso en sistemas que podrían tener usuarios que no son de confianza ejecutando código.

Consulte también

Se aplica a