AutoResetEvent Clase

Definición

Representa un evento de sincronización de subprocesos que, cuando se señala, libera un único subproceso en espera y el evento se restablece automáticamente. Si no hay ningún subproceso en espera, el siguiente subproceso que se establece en el estado de espera se libera inmediatamente y el evento se restablece automáticamente. Esta clase no puede heredarse.

public ref class AutoResetEvent sealed : System::Threading::EventWaitHandle
public ref class AutoResetEvent sealed : System::Threading::WaitHandle
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
public sealed class AutoResetEvent : System.Threading.WaitHandle
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
type AutoResetEvent = class
    inherit EventWaitHandle
type AutoResetEvent = class
    inherit WaitHandle
[<System.Runtime.InteropServices.ComVisible(true)>]
type AutoResetEvent = class
    inherit EventWaitHandle
Public NotInheritable Class AutoResetEvent
Inherits EventWaitHandle
Public NotInheritable Class AutoResetEvent
Inherits WaitHandle
Herencia
Herencia
Herencia
Atributos

Ejemplos

En el ejemplo siguiente se muestra cómo usar AutoResetEvent para liberar un subproceso a la vez, llamando al Set método (en la clase base) cada vez que el usuario presiona la tecla Entrar . En el ejemplo se inician tres subprocesos, que esperan en un AutoResetEvent objeto que se creó en el estado señalado. El primer subproceso se libera inmediatamente, ya AutoResetEvent que ya está en estado señalado. Esto restablece al AutoResetEvent estado no señalado, de modo que los subprocesos subsiguientes bloqueen. Los subprocesos bloqueados no se liberan hasta que el usuario los libera de uno en uno presionando la tecla Entrar .

Una vez que los subprocesos se liberan desde el primer AutoResetEvent, esperan en otro AutoResetEvent que se creó en el estado no señalado. Los tres subprocesos bloquean, por lo que se Set debe llamar al método tres veces para liberarlos todos.

using namespace System;
using namespace System::Threading;

ref class Example
{
private:
    static AutoResetEvent^ event_1 = gcnew AutoResetEvent(true);
    static AutoResetEvent^ event_2 = gcnew AutoResetEvent(false);

    static void ThreadProc()
    {
        String^ name = Thread::CurrentThread->Name;

        Console::WriteLine("{0} waits on AutoResetEvent #1.", name);
        event_1->WaitOne();
        Console::WriteLine("{0} is released from AutoResetEvent #1.", name);

        Console::WriteLine("{0} waits on AutoResetEvent #2.", name);
        event_2->WaitOne();
        Console::WriteLine("{0} is released from AutoResetEvent #2.", name);

        Console::WriteLine("{0} ends.", name);
    }

public:
    static void Demo()
    {
        Console::WriteLine("Press Enter to create three threads and start them.\r\n" +
                           "The threads wait on AutoResetEvent #1, which was created\r\n" +
                           "in the signaled state, so the first thread is released.\r\n" +
                           "This puts AutoResetEvent #1 into the unsignaled state.");
        Console::ReadLine();
            
        for (int i = 1; i < 4; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(&ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }
        Thread::Sleep(250);

        for (int i = 0; i < 2; i++)
        {
            Console::WriteLine("Press Enter to release another thread.");
            Console::ReadLine();
            event_1->Set();
            Thread::Sleep(250);
        }

        Console::WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2.");
        for (int i = 0; i < 3; i++)
        {
            Console::WriteLine("Press Enter to release a thread.");
            Console::ReadLine();
            event_2->Set();
            Thread::Sleep(250);
        }

        // Visual Studio: Uncomment the following line.
        //Console::Readline();
    }
};

void main()
{
    Example::Demo();
}

/* This example produces output similar to the following:

Press Enter to create three threads and start them.
The threads wait on AutoResetEvent #1, which was created
in the signaled state, so the first thread is released.
This puts AutoResetEvent #1 into the unsignaled state.

Thread_1 waits on AutoResetEvent #1.
Thread_1 is released from AutoResetEvent #1.
Thread_1 waits on AutoResetEvent #2.
Thread_3 waits on AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #1.
Press Enter to release another thread.

Thread_3 is released from AutoResetEvent #1.
Thread_3 waits on AutoResetEvent #2.
Press Enter to release another thread.

Thread_2 is released from AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #2.

All threads are now waiting on AutoResetEvent #2.
Press Enter to release a thread.

Thread_2 is released from AutoResetEvent #2.
Thread_2 ends.
Press Enter to release a thread.

Thread_1 is released from AutoResetEvent #2.
Thread_1 ends.
Press Enter to release a thread.

Thread_3 is released from AutoResetEvent #2.
Thread_3 ends.
 */
using System;
using System.Threading;

// Visual Studio: Replace the default class in a Console project with 
//                the following class.
class Example
{
    private static AutoResetEvent event_1 = new AutoResetEvent(true);
    private static AutoResetEvent event_2 = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("Press Enter to create three threads and start them.\r\n" +
                          "The threads wait on AutoResetEvent #1, which was created\r\n" +
                          "in the signaled state, so the first thread is released.\r\n" +
                          "This puts AutoResetEvent #1 into the unsignaled state.");
        Console.ReadLine();
            
        for (int i = 1; i < 4; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }
        Thread.Sleep(250);

        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine("Press Enter to release another thread.");
            Console.ReadLine();
            event_1.Set();
            Thread.Sleep(250);
        }

        Console.WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2.");
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Press Enter to release a thread.");
            Console.ReadLine();
            event_2.Set();
            Thread.Sleep(250);
        }

        // Visual Studio: Uncomment the following line.
        //Console.Readline();
    }

    static void ThreadProc()
    {
        string name = Thread.CurrentThread.Name;

        Console.WriteLine("{0} waits on AutoResetEvent #1.", name);
        event_1.WaitOne();
        Console.WriteLine("{0} is released from AutoResetEvent #1.", name);

        Console.WriteLine("{0} waits on AutoResetEvent #2.", name);
        event_2.WaitOne();
        Console.WriteLine("{0} is released from AutoResetEvent #2.", name);

        Console.WriteLine("{0} ends.", name);
    }
}

/* This example produces output similar to the following:

Press Enter to create three threads and start them.
The threads wait on AutoResetEvent #1, which was created
in the signaled state, so the first thread is released.
This puts AutoResetEvent #1 into the unsignaled state.

Thread_1 waits on AutoResetEvent #1.
Thread_1 is released from AutoResetEvent #1.
Thread_1 waits on AutoResetEvent #2.
Thread_3 waits on AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #1.
Press Enter to release another thread.

Thread_3 is released from AutoResetEvent #1.
Thread_3 waits on AutoResetEvent #2.
Press Enter to release another thread.

Thread_2 is released from AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #2.

All threads are now waiting on AutoResetEvent #2.
Press Enter to release a thread.

Thread_2 is released from AutoResetEvent #2.
Thread_2 ends.
Press Enter to release a thread.

Thread_1 is released from AutoResetEvent #2.
Thread_1 ends.
Press Enter to release a thread.

Thread_3 is released from AutoResetEvent #2.
Thread_3 ends.
 */
Imports System.Threading

' Visual Studio: Replace the default class in a Console project with 
'                the following class.
Class Example

    Private Shared event_1 As New AutoResetEvent(True)
    Private Shared event_2 As New AutoResetEvent(False)

    <MTAThread()> _
    Shared Sub Main()
    
        Console.WriteLine("Press Enter to create three threads and start them." & vbCrLf & _
                          "The threads wait on AutoResetEvent #1, which was created" & vbCrLf & _
                          "in the signaled state, so the first thread is released." & vbCrLf & _
                          "This puts AutoResetEvent #1 into the unsignaled state.")
        Console.ReadLine()
            
        For i As Integer = 1 To 3
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next
        Thread.Sleep(250)

        For i As Integer = 1 To 2
            Console.WriteLine("Press Enter to release another thread.")
            Console.ReadLine()

            event_1.Set()
            Thread.Sleep(250)
        Next

        Console.WriteLine(vbCrLf & "All threads are now waiting on AutoResetEvent #2.")
        For i As Integer = 1 To 3
            Console.WriteLine("Press Enter to release a thread.")
            Console.ReadLine()

            event_2.Set()
            Thread.Sleep(250)
        Next

        ' Visual Studio: Uncomment the following line.
        'Console.Readline()
    End Sub

    Shared Sub ThreadProc()
    
        Dim name As String = Thread.CurrentThread.Name

        Console.WriteLine("{0} waits on AutoResetEvent #1.", name)
        event_1.WaitOne()
        Console.WriteLine("{0} is released from AutoResetEvent #1.", name)

        Console.WriteLine("{0} waits on AutoResetEvent #2.", name)
        event_2.WaitOne()
        Console.WriteLine("{0} is released from AutoResetEvent #2.", name)

        Console.WriteLine("{0} ends.", name)
    End Sub
End Class

' This example produces output similar to the following:
'
'Press Enter to create three threads and start them.
'The threads wait on AutoResetEvent #1, which was created
'in the signaled state, so the first thread is released.
'This puts AutoResetEvent #1 into the unsignaled state.
'
'Thread_1 waits on AutoResetEvent #1.
'Thread_1 is released from AutoResetEvent #1.
'Thread_1 waits on AutoResetEvent #2.
'Thread_3 waits on AutoResetEvent #1.
'Thread_2 waits on AutoResetEvent #1.
'Press Enter to release another thread.
'
'Thread_3 is released from AutoResetEvent #1.
'Thread_3 waits on AutoResetEvent #2.
'Press Enter to release another thread.
'
'Thread_2 is released from AutoResetEvent #1.
'Thread_2 waits on AutoResetEvent #2.
'
'All threads are now waiting on AutoResetEvent #2.
'Press Enter to release a thread.
'
'Thread_2 is released from AutoResetEvent #2.
'Thread_2 ends.
'Press Enter to release a thread.
'
'Thread_1 is released from AutoResetEvent #2.
'Thread_1 ends.
'Press Enter to release a thread.
'
'Thread_3 is released from AutoResetEvent #2.
'Thread_3 ends.

Comentarios

AutoResetEventUse , ManualResetEventy EventWaitHandle para la interacción del subproceso (o señalización de subprocesos). Para obtener más información, consulte la sección Interacción del subproceso o señalización del artículo Información general sobre primitivos de sincronización .

Importante

Este tipo implementa la interfaz IDisposable. Cuando haya terminado de utilizar el tipo, debe desecharlo directa o indirectamente. Para eliminar el tipo directamente, llame a su método Dispose en un bloque try/catch. Para deshacerse de él indirectamente, use una construcción de lenguaje como using (en C#) o Using (en Visual Basic). Para más información, vea la sección "Uso de objetos que implementan IDisposable" en el tema de la interfaz IDisposable.

Un subproceso espera una señal llamando a AutoResetEvent.WaitOne. AutoResetEvent Si está en estado no señalado, el subproceso se bloquea hasta que se llame a AutoResetEvent.Set.

Llamar a Set señales para liberar un subproceso AutoResetEvent en espera. AutoResetEvent permanece señalado hasta que se libera un único subproceso en espera y, a continuación, vuelve automáticamente al estado no señalado. Si no hay subprocesos en espera, el estado permanece señalado indefinidamente.

Si un subproceso llama WaitOne mientras AutoResetEvent está en estado señalado, el subproceso no se bloquea. AutoResetEvent Libera el subproceso inmediatamente y vuelve al estado no señalado.

Importante

No hay ninguna garantía de que todas las llamadas al Set método liberarán un subproceso. Si dos llamadas están demasiado cerca, de modo que la segunda llamada se produzca antes de que se haya liberado un subproceso, solo se libera un subproceso. Es como si la segunda llamada no sucediera. Además, si Set se llama cuando no hay subprocesos en espera y AutoResetEvent ya está señalado, la llamada no tiene ningún efecto.

Puede controlar el estado inicial de un AutoResetEvent pasando un valor booleano al constructor: true si el estado inicial se señala y false de lo contrario.

AutoResetEvent también se puede usar con los staticWaitAll métodos y WaitAny .

A partir de la versión 2.0 de .NET Framework, AutoResetEvent se deriva de la nueva EventWaitHandle clase. Un AutoResetEvent es funcionalmente equivalente a un EventWaitHandle objeto creado con EventResetMode.AutoReset.

Nota

A diferencia de la AutoResetEvent clase , la EventWaitHandle clase proporciona acceso a eventos de sincronización del sistema con nombre.

Constructores

AutoResetEvent(Boolean)

Inicializa una nueva instancia de la clase AutoResetEvent con un valor booleano que indica si hay que establecer el estado inicial en señalado.

Campos

WaitTimeout

Indica que una operación WaitAny(WaitHandle[], Int32, Boolean) ha superado el tiempo de espera antes de que se señalara un identificador de espera. Este campo es constante.

(Heredado de WaitHandle)

Propiedades

Handle
Obsoletos.
Obsoletos.

Obtiene o establece el identificador del sistema operativo nativo.

(Heredado de WaitHandle)
SafeWaitHandle

Obtiene o establece el identificador del sistema operativo nativo.

(Heredado de WaitHandle)

Métodos

Close()

Libera todos los recursos mantenidos por el objeto WaitHandle actual.

(Heredado de WaitHandle)
CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.

(Heredado de MarshalByRefObject)
Dispose()

Libera todos los recursos usados por la instancia actual de la clase WaitHandle.

(Heredado de WaitHandle)
Dispose(Boolean)

Cuando se reemplaza en una clase derivada, libera los recursos no administrados que usa WaitHandle y, de forma opcional, libera los recursos administrados.

(Heredado de WaitHandle)
Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetAccessControl()

Obtiene un objeto EventWaitHandleSecurity que representa la seguridad de control de acceso para el evento del sistema con nombre representado por el objetoEventWaitHandle actual.

(Heredado de EventWaitHandle)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetLifetimeService()
Obsoletos.

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
InitializeLifetimeService()
Obsoletos.

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.

(Heredado de MarshalByRefObject)
Reset()

Establece el estado del evento en no señalado, por lo que se bloquean los subprocesos.

Reset()

Establece el estado del evento en no señalado, haciendo que los subprocesos se bloqueen.

(Heredado de EventWaitHandle)
Set()

Establece el estado del evento en señalado, lo que permite que uno o varios subprocesos en espera continúen.

Set()

Establece el estado del evento en señalado, permitiendo que uno o varios subprocesos en espera continúen.

(Heredado de EventWaitHandle)
SetAccessControl(EventWaitHandleSecurity)

Establece la seguridad de control de acceso para evento del sistema con nombre.

(Heredado de EventWaitHandle)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
WaitOne()

Bloquea el subproceso actual hasta que el objeto WaitHandle actual recibe una señal.

(Heredado de WaitHandle)
WaitOne(Int32)

Bloquea el subproceso actual hasta que el objeto WaitHandle actual recibe una señal, usando un entero de 32 bits con signo para especificar el intervalo de tiempo en milisegundos.

(Heredado de WaitHandle)
WaitOne(Int32, Boolean)

Bloquea el subproceso actual hasta que el objeto WaitHandle actual recibe una señal, usa un entero de 32 bits con signo para determinar el intervalo de tiempo y especifica si hay que salir del dominio de sincronización antes de la espera.

(Heredado de WaitHandle)
WaitOne(TimeSpan)

Bloquea el subproceso actual hasta que la instancia actual recibe una señal, usando TimeSpan para especificar el intervalo de tiempo.

(Heredado de WaitHandle)
WaitOne(TimeSpan, Boolean)

Bloquea el subproceso actual hasta que la instancia actual recibe una señal; usa TimeSpan para determinar el intervalo de tiempo y especifica si hay que abandonar el dominio de sincronización antes de la espera.

(Heredado de WaitHandle)

Implementaciones de interfaz explícitas

IDisposable.Dispose()

Esta API admite la infraestructura de producto y no está pensada para usarse directamente en el código.

Libera todos los recursos que usa WaitHandle.

(Heredado de WaitHandle)

Métodos de extensión

GetAccessControl(EventWaitHandle)

Devuelve los descriptores de seguridad para el objeto handle especificado.

SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)

Establece los descriptores de seguridad para el identificador de espera de eventos especificado.

GetSafeWaitHandle(WaitHandle)

Obtiene el controlador seguro para un identificador de espera del sistema operativo nativo.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Establece un controlador seguro para un identificador de espera del sistema operativo nativo.

Se aplica a

Seguridad para subprocesos

Esta clase es segura para subprocesos.

Consulte también