ManualResetEvent Classe

Definição

Representa um evento de sincronização de thread que, quando sinalizado, deve ser redefinido manualmente. Essa classe não pode ser herdada.

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
Herança
ManualResetEvent
Herança
Herança
Atributos

Exemplos

O exemplo a seguir demonstra como ManualResetEvent funciona. O exemplo começa com um ManualResetEvent estado sem sinal (ou seja, false é passado para o construtor). O exemplo cria três threads, cada um dos quais bloqueia chamando seu ManualResetEvent WaitOne método. Quando o usuário pressiona a tecla Enter , o exemplo chama o Set método, que libera todos os três threads. Contraste isso com o comportamento da AutoResetEvent classe, que libera threads um de cada vez, redefinindo automaticamente após cada versão.

Pressionar a tecla Enter novamente demonstra que os ManualResetEvent restos mortais no estado sinalizado até que seu Reset método seja chamado: O exemplo inicia mais dois threads. Esses threads não bloqueiam quando chamam o WaitOne método, mas são executados até a conclusão.

Pressionar a tecla Enter novamente faz com que o exemplo chame o Reset método e inicie mais um thread, que bloqueia quando ele chama WaitOne. Pressionando a tecla Enter uma última vez chama Set para liberar o último thread e o programa termina.

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.

Comentários

Você usa ManualResetEvente AutoResetEventEventWaitHandle para interação de thread (ou sinalização de thread). Para obter mais informações, consulte a interação do Thread ou a seção de sinalização do artigo Visão geral dos primitivos de sincronização .

Quando um thread inicia uma atividade que deve ser concluída antes que outros threads prossigam, ele chama ManualResetEvent.Reset para colocar ManualResetEvent no estado não sinalizado. Esse thread pode ser considerado como controlando o ManualResetEvent. Threads que chamam o bloco ManualResetEvent.WaitOne , aguardando o sinal. Quando o thread de controle conclui a atividade, ele chama ManualResetEvent.Set para sinalizar que os threads de espera podem continuar. Todos os threads de espera são liberados.

Depois de sinalizado, ManualResetEvent permanece sinalizado até ser redefinido manualmente chamando o Reset() método. Ou seja, chamadas para WaitOne retornar imediatamente.

Você pode controlar o estado inicial de um ManualResetEvent passando um valor booliano para o construtor: true se o estado inicial for sinalizado e false de outra forma.

ManualResetEventtambém pode ser usado com os métodos e WaitAny os static WaitAll métodos.

A partir do .NET Framework versão 2.0, ManualResetEvent deriva da EventWaitHandle classe. A ManualResetEvent é funcionalmente equivalente a um EventWaitHandle criado com EventResetMode.ManualReset.

Observação

Ao contrário da ManualResetEvent classe, a EventWaitHandle classe fornece acesso a eventos de sincronização do sistema nomeados.

A partir do .NET Framework versão 4.0, a System.Threading.ManualResetEventSlim classe é uma alternativa leve para ManualResetEvent.

Construtores

ManualResetEvent(Boolean)

Inicializa uma nova instância da classe ManualResetEvent com um valor booliano que indica se é necessário definir o estado inicial como sinalizado.

Campos

WaitTimeout

Indica que uma operação WaitAny(WaitHandle[], Int32, Boolean) atingiu o tempo limite antes que algum dos identificadores de espera fosse sinalizado. Este campo é constante.

(Herdado de WaitHandle)

Propriedades

Handle
Obsoleto.
Obsoleto.

Obtém ou define o identificador de sistema operacional nativo.

(Herdado de WaitHandle)
SafeWaitHandle

Obtém ou define o identificador de sistema operacional nativo.

(Herdado de WaitHandle)

Métodos

Close()

Libera todos os recursos mantidos pelo WaitHandle atual.

(Herdado de WaitHandle)
CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.

(Herdado de MarshalByRefObject)
Dispose()

Libera todos os recursos usados pela instância atual da classe WaitHandle.

(Herdado de WaitHandle)
Dispose(Boolean)

Quando substituído em uma classe derivada, libera os recursos não gerenciados usados pelo WaitHandle e, opcionalmente, libera os recursos gerenciados.

(Herdado de WaitHandle)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetAccessControl()

Obtém um objeto EventWaitHandleSecurity que representa a segurança de controle de acesso para o evento do sistema nomeado representado pelo objeto EventWaitHandle atual.

(Herdado de EventWaitHandle)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetLifetimeService()
Obsoleto.

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
InitializeLifetimeService()
Obsoleto.

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.

(Herdado de MarshalByRefObject)
Reset()

Define o estado do evento como não sinalizado, o que causa o bloqueio dos threads.

Reset()

Define o estado do evento como não sinalizado, fazendo com que os threads sejam bloqueados.

(Herdado de EventWaitHandle)
Set()

Define o estado do evento a ser sinalizado, permitindo que um ou mais threads de espera prossigam.

Set()

Define o estado do evento a ser sinalizado, permitindo que um ou mais threads de espera prossigam.

(Herdado de EventWaitHandle)
SetAccessControl(EventWaitHandleSecurity)

Define a segurança de controle de acesso para um evento do sistema nomeado.

(Herdado de EventWaitHandle)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)
WaitOne()

Bloqueia o thread atual até que o WaitHandle atual receba um sinal.

(Herdado de WaitHandle)
WaitOne(Int32)

Bloqueia o thread atual até que o WaitHandle atual receba um sinal, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo em milissegundos.

(Herdado de WaitHandle)
WaitOne(Int32, Boolean)

Bloqueia o thread atual até que o WaitHandle atual receba um sinal, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo e especificar se sairá do domínio de sincronização antes da espera.

(Herdado de WaitHandle)
WaitOne(TimeSpan)

Bloqueia o thread atual até que a instância atual receba um sinal, usando um TimeSpan para especificar o intervalo de tempo.

(Herdado de WaitHandle)
WaitOne(TimeSpan, Boolean)

Bloqueia o thread atual até que a instância atual receba um sinal, usando um TimeSpan para especificar o intervalo de tempo e especificar se sairá do domínio de sincronização antes da espera.

(Herdado de WaitHandle)

Implantações explícitas de interface

IDisposable.Dispose()

Esta API dá suporte à infraestrutura do produto e não deve ser usada diretamente do seu código.

Libera todos os recursos usados pelo WaitHandle.

(Herdado de WaitHandle)

Métodos de Extensão

GetAccessControl(EventWaitHandle)

Retorna os descritores de segurança para o handle especificado.

SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)

Define os descritores de segurança para o identificador de espera de evento especificado.

GetSafeWaitHandle(WaitHandle)

Obtém o identificador seguro para um identificador de espera nativo do sistema operacional.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Define um identificador seguro para um identificador de espera do sistema operacional nativo.

Aplica-se a

Acesso thread-safe

Essa classe é thread safe.

Confira também