AutoResetEvent Clase

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

En el ejemplo siguiente se muestra cómo AutoResetEvent utilizar para liberar un subproceso cada vez, llamando al Set método (en la clase base) cada vez que el usuario presiona la tecla entrar .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. En el ejemplo se inician tres subprocesos AutoResetEvent , que esperan en un 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 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 el objeto AutoResetEvent en el estado no señalado, de modo que los subprocesos subsiguientes se bloqueen.This resets the AutoResetEvent to the non-signaled state, so that subsequent threads block. Los subprocesos bloqueados no se liberan hasta que el usuario los libera de uno en uno presionando la tecla entrar .The blocked threads are not released until the user releases them one at a time by pressing the Enter key.

Una vez que los subprocesos se AutoResetEventliberan del primero, AutoResetEvent esperan en otro 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. Los tres subprocesos se bloquean, por lo que Set se debe llamar tres veces al método para liberarlos todos.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

Use AutoResetEvent, ManualResetEventy paralainteraccióndesubprocesos(oseñalizacióndesubprocesos).EventWaitHandleYou use AutoResetEvent, ManualResetEvent, and EventWaitHandle for thread interaction (or thread signaling). Para obtener más información, vea la sección interacción de subprocesos o señalización del artículo información general sobre los primitivos de sincronización .For more information, see the Thread interaction, or signaling section of the Overview of synchronization primitives article.

Importante

Este tipo implementa la interfaz IDisposable.This type implements the IDisposable interface. Cuando haya terminado de utilizar el tipo, debe desecharlo directa o indirectamente.When you have finished using the type, you should dispose of it either directly or indirectly. Para eliminar el tipo directamente, llame a su método Dispose en un bloque try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Para deshacerse de él indirectamente, use 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 más información, vea la sección "Uso de objetos que implementan IDisposable" en el tema de la interfaz IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

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

Llamar Set a AutoResetEvent las señales para liberar un subproceso en espera.Calling Set signals AutoResetEvent to release a waiting thread. AutoResetEventpermanece 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 WaitOne llama a AutoResetEvent mientras está en el estado señalado, el subproceso no se bloquea.If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block. 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 cada llamada al Set método liberará un subproceso.There is no guarantee that every call to the Set method will release a thread. Si dos llamadas son demasiado próximas juntas, de modo que la segunda llamada se produce antes de que se libere un subproceso, solo se libera un 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 a cuando no hay subprocesos en AutoResetEvent espera y ya está señalado, 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 una AutoResetEvent pasando un valor booleano al constructor: true si el estado inicial es señalado 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.

AutoResetEventtambién se puede utilizar con los static WaitAll métodos WaitAny y.AutoResetEvent can also be used with the static WaitAll and WaitAny methods.

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

Nota

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

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

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

(Heredado de WaitHandle)

Propiedades

Handle

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

(Heredado de WaitHandle)
SafeWaitHandle

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

(Heredado de WaitHandle)

Métodos

Close()

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

(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.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Heredado de MarshalByRefObject)
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.

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

(Heredado de WaitHandle)
Equals(Object)

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

(Heredado de Object)
GetHashCode()

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

(Heredado de Object)
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.

(Heredado de MarshalByRefObject)
GetType()

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

(Heredado de Object)
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.

(Heredado de MarshalByRefObject)
MemberwiseClone()

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

(Heredado de Object)
MemberwiseClone(Boolean)

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

(Heredado de MarshalByRefObject)
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()

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()

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

(Heredado de Object)
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.

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

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

(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.Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.

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

(Heredado de WaitHandle)

Implementaciones de interfaz explícitas

IDisposable.Dispose()

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

(Heredado de WaitHandle)

Métodos de extensión

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)

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: