EventWaitHandle Constructores

Definición

Inicializa una nueva instancia de la clase EventWaitHandle.

Sobrecargas

EventWaitHandle(Boolean, EventResetMode)

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente y si se restablece automática o manualmente.

EventWaitHandle(Boolean, EventResetMode, String)

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente cuando se crea como resultado de esta llamada, si se restablece automática o manualmente y el nombre de un evento de sincronización del sistema.

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente si se crea como resultado de esta llamada, si se restablece automática o manualmente, el nombre de un evento de sincronización del sistema y una variable booleana cuyo valor después de la llamada indica si se creó el evento del sistema con nombre.

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente si se crea como resultado de esta llamada, si se restablece automática o manualmente, el nombre de un evento de sincronización del sistema, una variable booleana cuyo valor después de la llamada indica si se creó el evento del sistema con nombre y la seguridad de control de acceso para aplicar al evento con nombre si se crea.

EventWaitHandle(Boolean, EventResetMode)

Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente y si se restablece automática o manualmente.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode)

Parámetros

initialState
Boolean

Es true para establecer el estado inicial en señalado; es false para establecerlo en no señalado.

mode
EventResetMode

Uno de los valores EventResetMode que determina si el evento se restablece automática o manualmente.

Excepciones

El valor de enumeración mode está fuera del intervalo válido.

Ejemplos

En el ejemplo de código siguiente se usa la sobrecarga del SignalAndWait(WaitHandle, WaitHandle) método para permitir que el subproceso principal indique un subproceso bloqueado y espere a que el subproceso finalice una tarea.

El ejemplo inicia cinco subprocesos y les permite bloquear en un EventWaitHandle creado con la EventResetMode.AutoReset marca y, a continuación, libera un subproceso cada vez que el usuario presiona la tecla Entrar . A continuación, en el ejemplo se ponen en cola otros cinco subprocesos y se liberan todos con un EventWaitHandle creado con la EventResetMode.ManualReset marca .

using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // The EventWaitHandle used to demonstrate the difference
   // between AutoReset and ManualReset synchronization events.
   //
   static EventWaitHandle^ ewh;

   // A counter to make sure all threads are started and
   // blocked before any are released. A Long is used to show
   // the use of the 64-bit Interlocked methods.
   //
   static __int64 threadCount = 0;

   // An AutoReset event that allows the main thread to block
   // until an exiting thread has decremented the count.
   //
   static EventWaitHandle^ clearCount =
      gcnew EventWaitHandle( false,EventResetMode::AutoReset );

public:
   [MTAThread]
   static void main()
   {
      // Create an AutoReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
      
      // Create and start five numbered threads. Use the
      // ParameterizedThreadStart delegate, so the thread
      // number can be passed as an argument to the Start
      // method.
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      // When multiple threads use a 64-bit value on a 32-bit
      // system, you must access the value through the
      // Interlocked class to guarantee thread safety.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Release one thread each time the user presses ENTER,
      // until all threads have been released.
      //
      while ( Interlocked::Read( threadCount ) > 0 )
      {
         Console::WriteLine( L"Press ENTER to release a waiting thread." );
         Console::ReadLine();
         
         // SignalAndWait signals the EventWaitHandle, which
         // releases exactly one thread before resetting,
         // because it was created with AutoReset mode.
         // SignalAndWait then blocks on clearCount, to
         // allow the signaled thread to decrement the count
         // before looping again.
         //
         WaitHandle::SignalAndWait( ewh, clearCount );
      }
      Console::WriteLine();
      
      // Create a ManualReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
      
      // Create and start five more numbered threads.
      //
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Because the EventWaitHandle was created with
      // ManualReset mode, signaling it releases all the
      // waiting threads.
      //
      Console::WriteLine( L"Press ENTER to release the waiting threads." );
      Console::ReadLine();
      ewh->Set();

   }

   static void ThreadProc( Object^ data )
   {
      int index = static_cast<Int32>(data);

      Console::WriteLine( L"Thread {0} blocks.", data );
      // Increment the count of blocked threads.
      Interlocked::Increment( threadCount );
      
      // Wait on the EventWaitHandle.
      ewh->WaitOne();

      Console::WriteLine( L"Thread {0} exits.", data );
      // Decrement the count of blocked threads.
      Interlocked::Decrement( threadCount );
      
      // After signaling ewh, the main thread blocks on
      // clearCount until the signaled thread has
      // decremented the count. Signal it now.
      //
      clearCount->Set();
   }
};
using System;
using System.Threading;

public class Example
{
    // The EventWaitHandle used to demonstrate the difference
    // between AutoReset and ManualReset synchronization events.
    //
    private static EventWaitHandle ewh;

    // A counter to make sure all threads are started and
    // blocked before any are released. A Long is used to show
    // the use of the 64-bit Interlocked methods.
    //
    private static long threadCount = 0;

    // An AutoReset event that allows the main thread to block
    // until an exiting thread has decremented the count.
    //
    private static EventWaitHandle clearCount = 
        new EventWaitHandle(false, EventResetMode.AutoReset);

    [MTAThread]
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

        // Create and start five numbered threads. Use the
        // ParameterizedThreadStart delegate, so the thread
        // number can be passed as an argument to the Start 
        // method.
        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting, 
            // because it was created with AutoReset mode. 
            // SignalAndWait then blocks on clearCount, to 
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();

        // Create a ManualReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        // Create and start five more numbered threads.
        //
        for(int i=0; i<=4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Because the EventWaitHandle was created with
        // ManualReset mode, signaling it releases all the
        // waiting threads.
        //
        Console.WriteLine("Press ENTER to release the waiting threads.");
        Console.ReadLine();
        ewh.Set();
    }

    public static void ThreadProc(object data)
    {
        int index = (int) data;

        Console.WriteLine("Thread {0} blocks.", data);
        // Increment the count of blocked threads.
        Interlocked.Increment(ref threadCount);

        // Wait on the EventWaitHandle.
        ewh.WaitOne();

        Console.WriteLine("Thread {0} exits.", data);
        // Decrement the count of blocked threads.
        Interlocked.Decrement(ref threadCount);

        // After signaling ewh, the main thread blocks on
        // clearCount until the signaled thread has 
        // decremented the count. Signal it now.
        //
        clearCount.Set();
    }
}
Imports System.Threading

Public Class Example

    ' The EventWaitHandle used to demonstrate the difference
    ' between AutoReset and ManualReset synchronization events.
    '
    Private Shared ewh As EventWaitHandle

    ' A counter to make sure all threads are started and
    ' blocked before any are released. A Long is used to show
    ' the use of the 64-bit Interlocked methods.
    '
    Private Shared threadCount As Long = 0

    ' An AutoReset event that allows the main thread to block
    ' until an exiting thread has decremented the count.
    '
    Private Shared clearCount As New EventWaitHandle(False, _
        EventResetMode.AutoReset)

    <MTAThread> _
    Public Shared Sub Main()

        ' Create an AutoReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.AutoReset)

        ' Create and start five numbered threads. Use the
        ' ParameterizedThreadStart delegate, so the thread
        ' number can be passed as an argument to the Start 
        ' method.
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        ' When multiple threads use a 64-bit value on a 32-bit
        ' system, you must access the value through the
        ' Interlocked class to guarantee thread safety.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Release one thread each time the user presses ENTER,
        ' until all threads have been released.
        '
        While Interlocked.Read(threadCount) > 0
            Console.WriteLine("Press ENTER to release a waiting thread.")
            Console.ReadLine()

            ' SignalAndWait signals the EventWaitHandle, which
            ' releases exactly one thread before resetting, 
            ' because it was created with AutoReset mode. 
            ' SignalAndWait then blocks on clearCount, to 
            ' allow the signaled thread to decrement the count
            ' before looping again.
            '
            WaitHandle.SignalAndWait(ewh, clearCount)
        End While
        Console.WriteLine()

        ' Create a ManualReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.ManualReset)

        ' Create and start five more numbered threads.
        '
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Because the EventWaitHandle was created with
        ' ManualReset mode, signaling it releases all the
        ' waiting threads.
        '
        Console.WriteLine("Press ENTER to release the waiting threads.")
        Console.ReadLine()
        ewh.Set()
        
    End Sub

    Public Shared Sub ThreadProc(ByVal data As Object)
        Dim index As Integer = CInt(data)

        Console.WriteLine("Thread {0} blocks.", data)
        ' Increment the count of blocked threads.
        Interlocked.Increment(threadCount)

        ' Wait on the EventWaitHandle.
        ewh.WaitOne()

        Console.WriteLine("Thread {0} exits.", data)
        ' Decrement the count of blocked threads.
        Interlocked.Decrement(threadCount)

        ' After signaling ewh, the main thread blocks on
        ' clearCount until the signaled thread has 
        ' decremented the count. Signal it now.
        '
        clearCount.Set()
    End Sub
End Class

Comentarios

Si el estado inicial del evento no tiene signo, se bloquearán los subprocesos que esperan en el evento. Si se señala el estado inicial y se especifica la marca para mode, los ManualReset subprocesos que esperan en el evento no se bloquearán. Si se señala el estado inicial y mode es AutoReset, el primer subproceso que espera en el evento se liberará inmediatamente, después del cual se restablecerá el evento y se bloquearán los subprocesos posteriores.

Consulte también

Se aplica a

EventWaitHandle(Boolean, EventResetMode, String)

Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente cuando se crea como resultado de esta llamada, si se restablece automática o manualmente y el nombre de un evento de sincronización del sistema.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String)

Parámetros

initialState
Boolean

true para establecer el estado inicial en señalado si el evento con nombre se crea como resultado de esta llamada; false para establecerlo en no señalado.

mode
EventResetMode

Uno de los valores EventResetMode que determina si el evento se restablece automática o manualmente.

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.

Atributos

Excepciones

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 evento con nombre existe y tiene seguridad de control de acceso, pero 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.

El valor de enumeración mode está fuera del intervalo válido.

O bien

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

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 abre 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.

Si ya existe un evento del sistema con el nombre especificado para el name parámetro , se omite el initialState parámetro .

Precaución

De forma predeterminada, un evento con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el evento, incluida la interferencia con el evento estableciendo o restableciendolo de forma inapropiada. Para restringir el acceso a usuarios específicos, puede usar una sobrecarga de constructor o EventWaitHandleAcl pasar una EventWaitHandleSecurity al crear el evento con nombre. Evite usar eventos con nombre sin restricciones de acceso en sistemas que puedan tener usuarios que no son de confianza que ejecuten código.

Importante

Al usar este constructor para eventos del sistema con nombre, especifique false para initialState. Este constructor no proporciona ninguna manera de determinar si se creó un evento del sistema con nombre, por lo que no se pueden realizar suposiciones sobre el estado del evento con nombre. Para determinar si se creó un evento con nombre, use el EventWaitHandle(Boolean, EventResetMode, String, Boolean) constructor o el EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity) constructor .

Si el estado inicial del evento no tiene signo, se bloquearán los subprocesos que esperan en el evento. Si se señala el estado inicial y se especifica la marca para mode, los ManualReset subprocesos que esperan en el evento no se bloquearán. Si se señala el estado inicial y mode es AutoReset, el primer subproceso que espera en el evento se liberará inmediatamente, después del cual se restablecerá el evento y se bloquearán los subprocesos posteriores.

Consulte también

Se aplica a

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente si se crea como resultado de esta llamada, si se restablece automática o manualmente, el nombre de un evento de sincronización del sistema y una variable booleana cuyo valor después de la llamada indica si se creó el evento del sistema con nombre.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean)

Parámetros

initialState
Boolean

true para establecer el estado inicial en señalado si el evento con nombre se crea como resultado de esta llamada; false para establecerlo en no señalado.

mode
EventResetMode

Uno de los valores EventResetMode que determina si el evento se restablece automática o manualmente.

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 ha creado un evento local (es decir, si name es null o una cadena vacía) o si se ha creado el evento del sistema con nombre especificado; es false si el evento del sistema con nombre especificado ya existía. Este parámetro se pasa sin inicializar.

Atributos

Excepciones

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 evento con nombre existe y tiene seguridad de control de acceso, pero 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.

El valor de enumeración mode está fuera del intervalo válido.

O bien

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

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 abre 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.

Si ya existe un evento del sistema con el nombre especificado para el name parámetro , se omite el initialState parámetro . Después de llamar a este constructor, use el valor de la variable especificada para el ref parámetro (ByRef parámetro en Visual Basic)createdNew para determinar si el evento del sistema con nombre ya existía o se creó.

Si el estado inicial del evento no tiene signo, se bloquearán los subprocesos que esperan en el evento. Si se señala el estado inicial y se especifica la marca para mode, los ManualReset subprocesos que esperan en el evento no se bloquearán. Si se señala el estado inicial y mode es AutoReset, el primer subproceso que espera en el evento se liberará inmediatamente, después del cual se restablecerá el evento y se bloquearán los subprocesos posteriores.

Precaución

De forma predeterminada, un evento con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el evento, incluida la interferencia con el evento estableciendo o restableciendolo de forma inapropiada. Para restringir el acceso a usuarios específicos, puede usar una sobrecarga de constructor o EventWaitHandleAcl pasar una EventWaitHandleSecurity al crear el evento con nombre. Evite usar eventos 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

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

Inicializa una nueva instancia de la clase EventWaitHandle, especificando si el identificador de espera se señala inicialmente si se crea como resultado de esta llamada, si se restablece automática o manualmente, el nombre de un evento de sincronización del sistema, una variable booleana cuyo valor después de la llamada indica si se creó el evento del sistema con nombre y la seguridad de control de acceso para aplicar al evento con nombre si se crea.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::EventWaitHandleSecurity ^ eventSecurity);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean, eventSecurity As EventWaitHandleSecurity)

Parámetros

initialState
Boolean

true para establecer el estado inicial en señalado si el evento con nombre se crea como resultado de esta llamada; false para establecerlo en no señalado.

mode
EventResetMode

Uno de los valores EventResetMode que determina si el evento se restablece automática o manualmente.

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 ha creado un evento local (es decir, si name es null o una cadena vacía) o si se ha creado el evento del sistema con nombre especificado; es false si el evento del sistema con nombre especificado ya existía. Este parámetro se pasa sin inicializar.

eventSecurity
EventWaitHandleSecurity

Objeto EventWaitHandleSecurity que representa la seguridad del control de acceso que se va a aplicar al evento del sistema con nombre.

Atributos

Excepciones

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 evento con nombre existe y tiene seguridad de control de acceso, pero 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.

El valor de enumeración mode está fuera del intervalo válido.

O bien

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

Ejemplos

En el ejemplo de código siguiente se muestra el comportamiento entre procesos de un evento del sistema 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 evento con nombre.

Si el evento no existe, se crea con la propiedad inicial y la seguridad de control de acceso que deniega al usuario actual el derecho de usar el evento, pero concede el derecho de leer y cambiar permisos en el evento.

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 a OpenExisting(String). La excepción se detecta y el ejemplo usa la OpenExisting(String, EventWaitHandleRights) sobrecarga del método para esperar en el evento con los derechos necesarios para leer y cambiar los permisos.

Después de cambiar los permisos, el evento se abre con los derechos necesarios para esperar en él y indicarlo. Si ejecuta el ejemplo compilado desde una tercera ventana de comandos, el ejemplo se ejecuta con los nuevos permisos.

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^ ewhName = L"EventWaitHandleExample5";

      EventWaitHandle^ ewh = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the event
      // constructor. It is true if the named system event was
      // created, and false if the named event already existed.
      //
      bool wasCreated;
      
      // Attempt to open the named event.
      try
      {
         // Open the event with (EventWaitHandleRights.Synchronize
         // | EventWaitHandleRights.Modify), to wait on and
         // signal the named event.
         //
         ewh = EventWaitHandle::OpenExisting( ewhName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Named event does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The event does not exist.
      // (2) The event exists, but the current user doesn't
      // have access. (3) The event exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The event does not exist, so create it.

         // Create an access control list (ACL) that denies the
         // current user the right to wait on or signal the
         // event, but allows the right to read and change
         // security information for the event.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         EventWaitHandleSecurity^ ewhSec = gcnew EventWaitHandleSecurity;
         //following constructor fails
         EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
            user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::Synchronize | 
               EventWaitHandleRights::Modify),
            AccessControlType::Deny );
         ewhSec->AddAccessRule( rule );

         rule = gcnew EventWaitHandleAccessRule( user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::ReadPermissions | 
               EventWaitHandleRights::ChangePermissions),
            AccessControlType::Allow );
         ewhSec->AddAccessRule( rule );
         
         // Create an EventWaitHandle object that represents
         // the system event named by the constant 'ewhName',
         // initially signaled, with automatic reset, and with
         // the specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in wasCreated.
         //
         ewh = gcnew EventWaitHandle( true,
            EventResetMode::AutoReset,
            ewhName,
            wasCreated,
            ewhSec );
         
         // If the named system event was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the event. Otherwise, exit the program.
         //
         if ( wasCreated )
         {
            Console::WriteLine( L"Created the named event." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the event." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the event to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            ewh = EventWaitHandle::OpenExisting( ewhName, 
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::ReadPermissions |
                  EventWaitHandleRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // EventWaitHandleRights.ReadPermissions.
            EventWaitHandleSecurity^ ewhSec = ewh->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 event must
            // be removed.
            EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
               user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Deny );
            ewhSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew EventWaitHandleAccessRule( user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Allow );
            ewhSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // EventWaitHandleRights.ChangePermissions.
            ewh->SetAccessControl( ewhSec );
            Console::WriteLine( L"Updated event security." );
            
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), the rights required
            // to wait on and signal the event.
            //
            ewh = EventWaitHandle::OpenExisting( ewhName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}",
               ex->Message );
            return;
         }

      }
      
      // Wait on the event, and hold it until the program
      // exits.
      //
      try
      {
         Console::WriteLine( L"Wait on the event." );
         ewh->WaitOne();
         Console::WriteLine( L"Event was signaled." );
         Console::WriteLine( L"Press the Enter key to signal the event and exit." );
         Console::ReadLine();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
      finally
      {
         ewh->Set();
      }
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the event
        // constructor. It is true if the named system event was
        // created, and false if the named event already existed.
        //
        bool wasCreated;

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The event does not exist.
        // (2) The event exists, but the current user doesn't 
        // have access. (3) The event exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

            // If the named system event was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the event. Otherwise, exit the program.
            // 
            if (wasCreated)
            {
                Console.WriteLine("Created the named event.");
            }
            else
            {
                Console.WriteLine("Unable to create the event.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the event to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                ewh = EventWaitHandle.OpenExisting(ewhName, 
                    EventWaitHandleRights.ReadPermissions | 
                    EventWaitHandleRights.ChangePermissions);

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

                Console.WriteLine("Updated event security.");

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const ewhName As String = "EventWaitHandleExample5"

        Dim ewh As EventWaitHandle = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the event
        ' constructor. It is True if the named system event was
        ' created, and False if the named event already existed.
        '
        Dim wasCreated As Boolean

        ' Attempt to open the named event.
        Try
            ' Open the event with (EventWaitHandleRights.Synchronize
            ' Or EventWaitHandleRights.Modify), to wait on and 
            ' signal the named event.
            '
            ewh = EventWaitHandle.OpenExisting(ewhName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Named event 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 event does not exist.
        ' (2) The event exists, but the current user doesn't 
        ' have access. (3) The event exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The event does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to wait on or signal the 
            ' event, but allows the right to read and change
            ' security information for the event.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim ewhSec As New EventWaitHandleSecurity()

            Dim rule As New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.Synchronize Or _
                EventWaitHandleRights.Modify, _
                AccessControlType.Deny)
            ewhSec.AddAccessRule(rule)

            rule = New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.ReadPermissions Or _
                EventWaitHandleRights.ChangePermissions, _
                AccessControlType.Allow)
            ewhSec.AddAccessRule(rule)

            ' Create an EventWaitHandle object that represents
            ' the system event named by the constant 'ewhName', 
            ' initially signaled, with automatic reset, and with
            ' the specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in wasCreated.
            '
            ewh = New EventWaitHandle(True, _
                EventResetMode.AutoReset, ewhName, _
                wasCreated, ewhSec)

            ' If the named system event was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the event. Otherwise, exit the program.
            ' 
            If wasCreated Then
                Console.WriteLine("Created the named event.")
            Else
                Console.WriteLine("Unable to create the event.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the event to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                ewh = EventWaitHandle.OpenExisting(ewhName, _
                    EventWaitHandleRights.ReadPermissions Or _
                    EventWaitHandleRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' EventWaitHandleRights.ReadPermissions.
                Dim ewhSec As EventWaitHandleSecurity = _
                    ewh.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the event must
                ' be removed.
                Dim rule As New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Deny)
                ewhSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Allow)
                ewhSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec)

                Console.WriteLine("Updated event security.")

                ' Open the event with (EventWaitHandleRights.Synchronize 
                ' Or EventWaitHandleRights.Modify), the rights required
                ' to wait on and signal the event.
                '
                ewh = EventWaitHandle.OpenExisting(ewhName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' Wait on the event, and hold it until the program
        ' exits.
        '
        Try
            Console.WriteLine("Wait on the event.")
            ewh.WaitOne()
            Console.WriteLine("Event was signaled.")
            Console.WriteLine("Press the Enter key to signal the event and exit.")
            Console.ReadLine()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        Finally
            ewh.Set()
        End Try
    End Sub 
End Class

Comentarios

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

Este constructor inicializa un EventWaitHandle objeto que representa un evento del sistema. Puede crear varios EventWaitHandle objetos que representen el mismo evento del sistema.

Si el evento del sistema no existe, se crea con la seguridad de control de acceso especificada. Si el evento existe, se omite la seguridad del control de acceso especificada.

Nota:

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

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 abre 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.

Si ya existe un evento del sistema con el nombre especificado para el name parámetro , se omite el initialState parámetro . Después de llamar a este constructor, use el valor de la variable especificada para el ref parámetro (ByRef parámetro en Visual Basic) createdNew para determinar si el evento del sistema con nombre ya existía o se creó.

Si el estado inicial del evento no tiene signo, se bloquearán los subprocesos que esperan en el evento. Si se señala el estado inicial y se especifica la marca para mode, los ManualReset subprocesos que esperan en el evento no se bloquearán. Si se señala el estado inicial y mode es AutoReset, el primer subproceso que espera en el evento se liberará inmediatamente, después del cual se restablecerá el evento y se bloquearán los subprocesos posteriores.

Precaución

De forma predeterminada, un evento con nombre no está restringido al usuario que lo creó. Es posible que otros usuarios puedan abrir y usar el evento, incluida la interferencia con el evento estableciendo o restableciendolo de forma inapropiada. Para restringir el acceso a usuarios específicos, puede pasar un EventWaitHandleSecurity al crear el evento con nombre. Evite usar eventos 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