Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase AutoResetEvent

 

Publicado: octubre de 2016

Notifica que se ha producido un evento a un subproceso en espera. Esta clase no puede heredarse.

Espacio de nombres:   System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.MarshalByRefObject
    System.Threading.WaitHandle
      System.Threading.EventWaitHandle
        System.Threading.AutoResetEvent

[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public sealed class AutoResetEvent : EventWaitHandle

NombreDescripción
System_CAPS_pubmethodAutoResetEvent(Boolean)

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

NombreDescripción
System_CAPS_pubpropertyHandle

Obsoleto.Obtiene o establece el identificador del sistema operativo nativo.(Heredado de WaitHandle).

System_CAPS_pubpropertySafeWaitHandle

Obtiene o establece el identificador del sistema operativo nativo.(Heredado de WaitHandle).

NombreDescripción
System_CAPS_pubmethodClose()

Libera todos los recursos mantenidos por el objeto WaitHandle actual.(Heredado de WaitHandle).

System_CAPS_pubmethodCreateObjRef(Type)

Crea un objeto que contiene toda la información pertinente necesaria para generar a un proxy utilizado para comunicarse con un objeto remoto.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodDispose()

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

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_pubmethodGetAccessControl()

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

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetLifetimeService()

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

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethodInitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodReset()

Establece el estado del evento en no señalado, por lo que se bloquean los subprocesos.(Heredado de EventWaitHandle).

System_CAPS_pubmethodSet()

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

System_CAPS_pubmethodSetAccessControl(EventWaitHandleSecurity)

Establece la seguridad de control de acceso para evento del sistema con nombre.(Heredado de EventWaitHandle).

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

System_CAPS_pubmethodWaitOne()

Bloquea el subproceso actual hasta que el objeto WaitHandle actual recibe una señal.(Heredado de WaitHandle).

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

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

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

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

NombreDescripción
System_CAPS_pubmethodGetSafeWaitHandle()

Obtiene el identificador seguro para un identificador de espera del sistema operativo nativo.(Definido por WaitHandleExtensions).

System_CAPS_pubmethodSetSafeWaitHandle(SafeWaitHandle)

Establece un controlador seguro para un identificador de espera del sistema operativo nativo.(Definido por WaitHandleExtensions).

AutoResetEvent allows threads to communicate with each other by signaling. Typically, you use this class when threads need exclusive access to a resource.

System_CAPS_importantImportante

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

A thread waits for a signal by calling M:System.Threading.WaitHandle.WaitOne(System.Int32,System.Boolean) on the AutoResetEvent. If the AutoResetEvent is in the non-signaled state, the thread blocks, waiting for the thread that currently controls the resource to signal that the resource is available by calling M:System.Threading.EventWaitHandle.Set.

Calling Set signals AutoResetEvent to release a waiting thread. AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. If no threads are waiting, the state remains signaled indefinitely.

If a thread calls M:System.Threading.WaitHandle.WaitOne(System.Int32,System.Boolean) while the T:System.Threading.AutoResetEvent is in the signaled state, the thread does not block. The T:System.Threading.AutoResetEvent releases the thread immediately and returns to the non-signaled state.

System_CAPS_importantImportante

There is no guarantee that every call to the M:System.Threading.EventWaitHandle.Set method will release a thread. If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released. It is as if the second call did not happen. Also, if M:System.Threading.EventWaitHandle.Set is called when there are no threads waiting and the T:System.Threading.AutoResetEvent is already signaled, the call has no effect.

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 can also be used with the staticWaitAll and WaitAny methods.

For more information about thread synchronization mechanisms, see AutoResetEvent in the conceptual documentation.

Beginning with the .NET Framework version 2.0, T:System.Threading.AutoResetEvent derives from the new T:System.Threading.EventWaitHandle class. An T:System.Threading.AutoResetEvent is functionally equivalent to an T:System.Threading.EventWaitHandle created with F:System.Threading.EventResetMode.AutoReset.

System_CAPS_noteNota

Unlike the T:System.Threading.AutoResetEvent class, the T:System.Threading.EventWaitHandle class provides access to named system synchronization events.

The following example shows how to use T:System.Threading.AutoResetEvent to release one thread at a time, by calling the M:System.Threading.EventWaitHandle.Set method (on the base class) each time the user presses the Enter key. The example starts three threads, which wait on an T:System.Threading.AutoResetEvent that was created in the signaled state. The first thread is released immediately, because the T:System.Threading.AutoResetEvent is already in the signaled state. This resets the T:System.Threading.AutoResetEvent to the non-signaled state, so that subsequent threads block. The blocked threads are not released until the user releases them one at a time by pressing the Enter key.

After the threads are released from the first T:System.Threading.AutoResetEvent, they wait on another T:System.Threading.AutoResetEvent that was created in the non-signaled state. All three threads block, so the M:System.Threading.EventWaitHandle.Set method must be called three times to release them all.

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

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

This class is thread safe.

Volver al principio
Mostrar: