Compartir a través de


ManualResetEvent Clase

Definición

Representa un evento de sincronización de subprocesos que, cuando se señala, debe restablecerse manualmente. Esta clase no se puede heredar.

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

Ejemplos

En el ejemplo siguiente se muestra cómo funciona ManualResetEvent. El ejemplo comienza con un ManualResetEvent en el estado sin signo (es decir, false se pasa al constructor). En el ejemplo se crean tres subprocesos, cada uno de los cuales se bloquea en el ManualResetEvent llamando a su método WaitOne. Cuando el usuario presiona el tecla Entrar, el ejemplo llama al método Set, que libera los tres subprocesos. Contrasta esto con el comportamiento de la clase AutoResetEvent, que libera subprocesos de uno en uno, restableciendo automáticamente después de cada versión.

Al presionar el tecla Entrar de nuevo se muestra que el ManualResetEvent permanece en estado señalado hasta que se llama a su método Reset: en el ejemplo se inician dos subprocesos más. Estos subprocesos no se bloquean cuando llaman al método WaitOne, sino que se ejecutan hasta la finalización.

Al presionar el tecla Entrar de nuevo, el ejemplo llama al método Reset e inicia un subproceso más, que se bloquea cuando llama a WaitOne. Al presionar el tecla Entrar una última vez, se llama a Set para liberar el último subproceso y finaliza el programa.

using namespace System;
using namespace System::Threading;

ref class Example
{
private:
    // mre is used to block and release threads manually. It is
    // created in the unsignaled state.
    static ManualResetEvent^ mre = gcnew ManualResetEvent(false);

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

        Console::WriteLine(name + " starts and calls mre->WaitOne()");

        mre->WaitOne();

        Console::WriteLine(name + " ends.");
    }

public:
    static void Demo()
    {
        Console::WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");

        for(int i = 0; i <=2 ; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }

        Thread::Sleep(500);
        Console::WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
                           "\nto release all the threads.\n");
        Console::ReadLine();

        mre->Set();

        Thread::Sleep(500);
        Console::WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
                           "\ndo not block. Press Enter to show this.\n");
        Console::ReadLine();

        for(int i = 3; i <= 4; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }

        Thread::Sleep(500);
        Console::WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
                           "\nwhen they call WaitOne().\n");
        Console::ReadLine();

        mre->Reset();

        // Start a thread that waits on the ManualResetEvent.
        Thread^ t5 = gcnew Thread(gcnew ThreadStart(ThreadProc));
        t5->Name = "Thread_5";
        t5->Start();

        Thread::Sleep(500);
        Console::WriteLine("\nPress Enter to call Set() and conclude the demo.");
        Console::ReadLine();

        mre->Set();

        // If you run this example in Visual Studio, uncomment the following line:
        //Console::ReadLine();
    }
};

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

/* This example produces output similar to the following:

Start 3 named threads that block on a ManualResetEvent:

Thread_0 starts and calls mre->WaitOne()
Thread_1 starts and calls mre->WaitOne()
Thread_2 starts and calls mre->WaitOne()

When all three threads have started, press Enter to call Set()
to release all the threads.


Thread_2 ends.
Thread_1 ends.
Thread_0 ends.

When a ManualResetEvent is signaled, threads that call WaitOne()
do not block. Press Enter to show this.


Thread_3 starts and calls mre->WaitOne()
Thread_3 ends.
Thread_4 starts and calls mre->WaitOne()
Thread_4 ends.

Press Enter to call Reset(), so that threads once again block
when they call WaitOne().


Thread_5 starts and calls mre->WaitOne()

Press Enter to call Set() and conclude the demo.

Thread_5 ends.
 */
using System;
using System.Threading;

public class Example
{
    // mre is used to block and release threads manually. It is
    // created in the unsignaled state.
    private static ManualResetEvent mre = new ManualResetEvent(false);

    static void Main()
    {
        Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");

        for(int i = 0; i <= 2; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }

        Thread.Sleep(500);
        Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
                          "\nto release all the threads.\n");
        Console.ReadLine();

        mre.Set();

        Thread.Sleep(500);
        Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
                          "\ndo not block. Press Enter to show this.\n");
        Console.ReadLine();

        for(int i = 3; i <= 4; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }

        Thread.Sleep(500);
        Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
                          "\nwhen they call WaitOne().\n");
        Console.ReadLine();

        mre.Reset();

        // Start a thread that waits on the ManualResetEvent.
        Thread t5 = new Thread(ThreadProc);
        t5.Name = "Thread_5";
        t5.Start();

        Thread.Sleep(500);
        Console.WriteLine("\nPress Enter to call Set() and conclude the demo.");
        Console.ReadLine();

        mre.Set();

        // If you run this example in Visual Studio, uncomment the following line:
        //Console.ReadLine();
    }

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

        Console.WriteLine(name + " starts and calls mre.WaitOne()");

        mre.WaitOne();

        Console.WriteLine(name + " ends.");
    }
}

/* This example produces output similar to the following:

Start 3 named threads that block on a ManualResetEvent:

Thread_0 starts and calls mre.WaitOne()
Thread_1 starts and calls mre.WaitOne()
Thread_2 starts and calls mre.WaitOne()

When all three threads have started, press Enter to call Set()
to release all the threads.


Thread_2 ends.
Thread_0 ends.
Thread_1 ends.

When a ManualResetEvent is signaled, threads that call WaitOne()
do not block. Press Enter to show this.


Thread_3 starts and calls mre.WaitOne()
Thread_3 ends.
Thread_4 starts and calls mre.WaitOne()
Thread_4 ends.

Press Enter to call Reset(), so that threads once again block
when they call WaitOne().


Thread_5 starts and calls mre.WaitOne()

Press Enter to call Set() and conclude the demo.

Thread_5 ends.
 */
Imports System.Threading

Public Class Example

    ' mre is used to block and release threads manually. It is
    ' created in the unsignaled state.
    Private Shared mre As New ManualResetEvent(False)

    <MTAThreadAttribute> _
    Shared Sub Main()

        Console.WriteLine(vbLf & _
            "Start 3 named threads that block on a ManualResetEvent:" & vbLf)

        For i As Integer = 0 To 2
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next i

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "When all three threads have started, press Enter to call Set()" & vbLf & _
            "to release all the threads." & vbLf)
        Console.ReadLine()

        mre.Set()

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "When a ManualResetEvent is signaled, threads that call WaitOne()" & vbLf & _
            "do not block. Press Enter to show this." & vbLf)
        Console.ReadLine()

        For i As Integer = 3 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next i

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "Press Enter to call Reset(), so that threads once again block" & vbLf & _
            "when they call WaitOne()." & vbLf)
        Console.ReadLine()

        mre.Reset()

        ' Start a thread that waits on the ManualResetEvent.
        Dim t5 As New Thread(AddressOf ThreadProc)
        t5.Name = "Thread_5"
        t5.Start()

        Thread.Sleep(500)
        Console.WriteLine(vbLf & "Press Enter to call Set() and conclude the demo.")
        Console.ReadLine()

        mre.Set()

        ' If you run this example in Visual Studio, uncomment the following line:
        'Console.ReadLine()

    End Sub


    Private Shared Sub ThreadProc()

        Dim name As String = Thread.CurrentThread.Name

        Console.WriteLine(name & " starts and calls mre.WaitOne()")

        mre.WaitOne()

        Console.WriteLine(name & " ends.")

    End Sub

End Class

' This example produces output similar to the following:
'
'Start 3 named threads that block on a ManualResetEvent:
'
'Thread_0 starts and calls mre.WaitOne()
'Thread_1 starts and calls mre.WaitOne()
'Thread_2 starts and calls mre.WaitOne()
'
'When all three threads have started, press Enter to call Set()
'to release all the threads.
'
'
'Thread_2 ends.
'Thread_0 ends.
'Thread_1 ends.
'
'When a ManualResetEvent is signaled, threads that call WaitOne()
'do not block. Press Enter to show this.
'
'
'Thread_3 starts and calls mre.WaitOne()
'Thread_3 ends.
'Thread_4 starts and calls mre.WaitOne()
'Thread_4 ends.
'
'Press Enter to call Reset(), so that threads once again block
'when they call WaitOne().
'
'
'Thread_5 starts and calls mre.WaitOne()
'
'Press Enter to call Set() and conclude the demo.
'
'Thread_5 ends.

Comentarios

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

Cuando un subproceso comienza una actividad que debe completarse antes de que continúen otros subprocesos, llama a ManualResetEvent.Reset para colocar ManualResetEvent en estado no señalado. Este subproceso se puede considerar como controlar el ManualResetEvent. Subprocesos que llaman a bloque ManualResetEvent.WaitOne, esperando la señal. Cuando el subproceso de control completa la actividad, llama a ManualResetEvent.Set para indicar que los subprocesos en espera pueden continuar. Se liberan todos los subprocesos en espera.

Una vez que se ha señalado, ManualResetEvent permanece señalado hasta que se restablece manualmente llamando al método Reset(). Es decir, las llamadas a WaitOne devuelven inmediatamente.

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

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

A partir de la versión 2.0 de .NET Framework, ManualResetEvent deriva de la clase EventWaitHandle. Un ManualResetEvent es funcionalmente equivalente a un EventWaitHandle creado con EventResetMode.ManualReset.

Nota

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

A partir de .NET Framework versión 4.0, la clase System.Threading.ManualResetEventSlim es una alternativa ligera a ManualResetEvent.

Constructores

ManualResetEvent(Boolean)

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

Campos

WaitTimeout

Indica que se ha agotado el tiempo de espera de una operación WaitAny(WaitHandle[], Int32, Boolean) antes de que se señalizara cualquiera de los identificadores 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 WaitHandleactual.

(Heredado de WaitHandle)
CreateObjRef(Type)

Crea un objeto que contiene toda la información pertinente necesaria para generar un proxy usado 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 usados por el WaitHandley, opcionalmente, libera los recursos administrados.

(Heredado de WaitHandle)
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetAccessControl()

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

(Heredado de EventWaitHandle)
GetHashCode()

Actúa como 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 Objectactual.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.

(Heredado de MarshalByRefObject)
Reset()

Establece el estado del evento en no asignado, lo que hace que los subprocesos se bloqueen.

Reset()

Establece el estado del evento en no asignado, lo que provoca que los subprocesos se bloqueen.

(Heredado de EventWaitHandle)
Set()

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

Set()

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

(Heredado de EventWaitHandle)
SetAccessControl(EventWaitHandleSecurity)

Establece la seguridad del control de acceso para un 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 WaitHandle actual recibe una señal.

(Heredado de WaitHandle)
WaitOne(Int32)

Bloquea el subproceso actual hasta que el WaitHandle actual recibe una señal, utilizando 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 WaitHandle actual recibe una señal, utilizando un entero de 32 bits con signo para especificar el intervalo de tiempo y especificar si se sale 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 mediante un 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, usando un TimeSpan para especificar el intervalo de tiempo y especificando si se sale del 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 usados por el WaitHandle.

(Heredado de WaitHandle)

Métodos de extensión

GetAccessControl(EventWaitHandle)

Devuelve los descriptores de seguridad del handleespecificado.

SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)

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

GetSafeWaitHandle(WaitHandle)

Obtiene el identificador seguro de un identificador de espera de sistema operativo nativo.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

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

Se aplica a

Seguridad para subprocesos

Esta clase es segura para subprocesos.

Consulte también