AutoResetEvent AutoResetEvent AutoResetEvent AutoResetEvent Class

Definición

Representa un evento de sincronización de subprocesos que cuando se señala, se restablece automáticamente después de liberar un único subproceso en espera.Represents a thread synchronization event that, when signaled, resets automatically after releasing a single waiting thread. Esta clase no puede heredarse.This class cannot be inherited.

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

Ejemplos

El ejemplo siguiente muestra cómo usar AutoResetEvent para liberar un subproceso a la vez, mediante una llamada a la Set método (en la clase base) cada vez el usuario presiona el ENTRAR clave.The following example shows how to use AutoResetEvent to release one thread at a time, by calling the Set method (on the base class) each time the user presses the Enter key. El ejemplo inicia tres subprocesos, lo que esperan un AutoResetEvent que se creó en el estado señalado.The example starts three threads, which wait on an AutoResetEvent that was created in the signaled state. El primer subproceso se libera inmediatamente, porque el AutoResetEvent ya está en el estado señalado.The first thread is released immediately, because the AutoResetEvent is already in the signaled state. Esto restablece la AutoResetEvent al estado no señalado, por lo que bloquean los subprocesos subsiguientes.This resets the AutoResetEvent to the non-signaled state, so that subsequent threads block. Los subprocesos bloqueados no se liberan hasta que el usuario libera uno en un momento presionando el ENTRAR clave.The blocked threads are not released until the user releases them one at a time by pressing the Enter key.

Después de que los subprocesos se liberan desde la primera AutoResetEvent, esperan en otro AutoResetEvent que se creó en el estado no señalado.After the threads are released from the first AutoResetEvent, they wait on another AutoResetEvent that was created in the non-signaled state. Bloquean los tres subprocesos, por lo que el Set método debe llamarse tres veces para liberar todos ellos.All three threads block, so the Set method must be called three times to release them all.

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

Usa AutoResetEvent, ManualResetEvent, y EventWaitHandle para la interacción de los subprocesos (o señalización de subproceso).You use AutoResetEvent, ManualResetEvent, and EventWaitHandle for thread interaction (or thread signaling). Para obtener más información, consulte el subprocesos interacción o señalización sección de la información general de las primitivas de sincronización artículo.For more information, see the Thread interaction, or signaling section of the Overview of synchronization primitives article.

Importante

Este tipo implementa la IDisposable interfaz.This type implements the IDisposable interface. Cuando haya terminado de utilizar el tipo, debe deshacerse de él directa o indirectamente.When you have finished using the type, you should dispose of it either directly or indirectly. Para deshacerse del tipo directamente, llame a su Dispose método en un try / catch bloque.To dispose of the type directly, call its Dispose method in a try/catch block. Para deshacerse de él, indirectamente, usar una construcción de lenguaje, como using (en C#) o Using (en Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Para obtener más información, vea la sección "Uso de un objeto que implementa IDisposable" en el IDisposable tema de la interfaz.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Un subproceso espera una señal mediante una llamada a AutoResetEvent.WaitOne.A thread waits for a signal by calling AutoResetEvent.WaitOne. Si el AutoResetEvent está en estado no señalado, el subproceso se bloquea hasta que AutoResetEvent.Set se llama.If the AutoResetEvent is in the non-signaled state, the thread blocks until AutoResetEvent.Set is called.

Una llamada a Set señales AutoResetEvent para liberar un subproceso en espera.Calling Set signals AutoResetEvent to release a waiting thread. 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.AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. Si no hay ningún subproceso en espera, el estado permanece señalado indefinidamente.If no threads are waiting, the state remains signaled indefinitely.

Si un subproceso llama WaitOne mientras el AutoResetEvent está en el estado señalado, no bloquea el subproceso.If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block. El AutoResetEvent libera el subproceso inmediatamente y vuelve al estado no señalado.The AutoResetEvent releases the thread immediately and returns to the non-signaled state.

Importante

No hay ninguna garantía de que todas las llamadas a la Set método liberará un subproceso.There is no guarantee that every call to the Set method will release a thread. Si dos llamadas están demasiado cerca, para que la segunda llamada se produce antes de que se ha liberado un subproceso, se libera un solo subproceso.If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released. Es como si no se produjera la segunda llamada.It's as if the second call did not happen. Además, si Set se llama cuando no hay ningún subproceso en espera y el AutoResetEvent ya está señalizado, la llamada no tiene ningún efecto.Also, if Set is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect.

Puede controlar el estado inicial de un AutoResetEvent pasando un valor booleano al constructor: true si señala el estado inicial y false en caso contrario.You can control the initial state of an AutoResetEvent by passing a Boolean value to the constructor: true if the initial state is signaled and false otherwise.

AutoResetEvent También puede utilizarse con el static WaitAll y WaitAny métodos.AutoResetEvent can also be used with the static WaitAll and WaitAny methods.

A partir de .NET Framework versión 2.0, AutoResetEvent se deriva de la nueva EventWaitHandle clase.Beginning with the .NET Framework version 2.0, AutoResetEvent derives from the new EventWaitHandle class. Un AutoResetEvent es funcionalmente equivalente a un EventWaitHandle creado con EventResetMode.AutoReset.An AutoResetEvent is functionally equivalent to an EventWaitHandle created with EventResetMode.AutoReset.

Nota

A diferencia de la AutoResetEvent (clase), el EventWaitHandle clase proporciona acceso a los eventos de sincronización de sistema con nombre.Unlike the AutoResetEvent class, the EventWaitHandle class provides access to named system synchronization events.

Constructores

AutoResetEvent(Boolean) AutoResetEvent(Boolean) AutoResetEvent(Boolean) 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.Initializes a new instance of the AutoResetEvent class with a Boolean value indicating whether to set the initial state to signaled.

Métodos

Close() Close() Close() Close()

Libera todos los recursos mantenidos por el objeto WaitHandle actual.Releases all resources held by the current WaitHandle.

(Inherited from WaitHandle)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos usados por la instancia actual de la clase WaitHandle.Releases all resources used by the current instance of the WaitHandle class.

(Inherited from WaitHandle)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) 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.When overridden in a derived class, releases the unmanaged resources used by the WaitHandle, and optionally releases the managed resources.

(Inherited from WaitHandle)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Reset() Reset() Reset() Reset()

Establece el estado del evento en no señalado, por lo que se bloquean los subprocesos.Sets the state of the event to nonsignaled, which causes threads to block.

Set() Set() Set() Set()

Establece el estado del evento en señalado, lo que permite que uno o varios subprocesos en espera continúen.Sets the state of the event to signaled, which allows at most one waiting thread to proceed.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
WaitOne() WaitOne() WaitOne() WaitOne()

Bloquea el subproceso actual hasta que el objeto WaitHandle actual recibe una señal.Blocks the current thread until the current WaitHandle receives a signal.

(Inherited from WaitHandle)
WaitOne(Int32) WaitOne(Int32) WaitOne(Int32) 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.Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval in milliseconds.

(Inherited from WaitHandle)
WaitOne(Int32, Boolean) WaitOne(Int32, Boolean) WaitOne(Int32, Boolean) 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.Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval and specifying whether to exit the synchronization domain before the wait.

(Inherited from WaitHandle)
WaitOne(TimeSpan) WaitOne(TimeSpan) WaitOne(TimeSpan) WaitOne(TimeSpan)

Bloquea el subproceso actual hasta que la instancia actual recibe una señal, usando TimeSpan para especificar el intervalo de tiempo.Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.

(Inherited from WaitHandle)
WaitOne(TimeSpan, Boolean) WaitOne(TimeSpan, Boolean) WaitOne(TimeSpan, Boolean) 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.Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.

(Inherited from WaitHandle)

Propiedades

Handle Handle Handle Handle

Obtiene o establece el identificador del sistema operativo nativo.Gets or sets the native operating system handle.

(Inherited from WaitHandle)
SafeWaitHandle SafeWaitHandle SafeWaitHandle SafeWaitHandle

Obtiene o establece el identificador del sistema operativo nativo.Gets or sets the native operating system handle.

(Inherited from WaitHandle)

Implementaciones de interfaz explícitas

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Libera todos los recursos que usa WaitHandle.Releases all resources used by the WaitHandle.

(Inherited from WaitHandle)

Campos

WaitTimeout WaitTimeout WaitTimeout 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.Indicates that a WaitAny(WaitHandle[], Int32, Boolean) operation timed out before any of the wait handles were signaled. Este campo es constante.This field is constant.

(Inherited from WaitHandle)

Métodos de extensión

GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle)

Obtiene el identificador seguro para un identificador de espera del sistema operativo nativo.Gets the safe handle for a native operating system wait handle.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Establece un controlador seguro para un identificador de espera del sistema operativo nativo.Sets a safe handle for a native operating system wait handle.

Se aplica a

Seguridad para subprocesos

Esta clase es segura para subprocesos.This class is thread safe.

Consulte también: