ManualResetEvent ManualResetEvent ManualResetEvent ManualResetEvent Class

Définition

Représente un événement de synchronisation de thread qui, quand il est signalé, doit être réinitialisé manuellement.Represents a thread synchronization event that, when signaled, must be reset manually. Cette classe ne peut pas être héritée.This class cannot be inherited.

public ref class ManualResetEvent sealed : System::Threading::EventWaitHandle
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ManualResetEvent : System.Threading.EventWaitHandle
type ManualResetEvent = class
    inherit EventWaitHandle
Public NotInheritable Class ManualResetEvent
Inherits EventWaitHandle
Héritage
Attributs

Exemples

L’exemple suivant illustre ManualResetEvent le fonctionnement de.The following example demonstrates how ManualResetEvent works. L’exemple commence par un ManualResetEvent dans l’état non signalé (c’est-à-dire, false est passé au constructeur).The example starts with a ManualResetEvent in the unsignaled state (that is, false is passed to the constructor). L’exemple crée trois threads, chacun d’entre eux bloquant ManualResetEvent sur le en WaitOne appelant sa méthode.The example creates three threads, each of which blocks on the ManualResetEvent by calling its WaitOne method. Quand l’utilisateur appuie sur la touche entrée , l’exemple appelle la Set méthode, qui libère les trois threads.When the user presses the Enter key, the example calls the Set method, which releases all three threads. Comparez ceci avec le comportement de AutoResetEvent la classe, qui libère les threads un par un, en réinitialisant automatiquement après chaque version.Contrast this with the behavior of the AutoResetEvent class, which releases threads one at a time, resetting automatically after each release.

Le fait **** d’appuyer à nouveau sur la ManualResetEvent touche entrée montre que le reste dans l' Reset état signalé jusqu’à ce que sa méthode soit appelée: L’exemple démarre deux threads supplémentaires.Pressing the Enter key again demonstrates that the ManualResetEvent remains in the signaled state until its Reset method is called: The example starts two more threads. Ces threads ne se bloquent pas lorsqu' WaitOne ils appellent la méthode, mais sont exécutés jusqu’à leur achèvement.These threads do not block when they call the WaitOne method, but instead run to completion.

Si vous appuyez de nouveau sur la touche entrée , l' Reset exemple appelle la méthode et démarre un thread supplémentaire, qui se bloque lors de l’appel WaitOnede.Pressing the Enter key again causes the example to call the Reset method and to start one more thread, which blocks when it calls WaitOne. En appuyant sur la touche entrée , Set une dernière fois appelle pour libérer le dernier thread et le programme se termine.Pressing the Enter key one final time calls Set to release the last thread, and the program ends.

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.

Remarques

Vous utilisez ManualResetEvent, AutoResetEventet EventWaitHandle pour l’interaction de thread (ou la signalisation de thread).You use ManualResetEvent, AutoResetEvent, and EventWaitHandle for thread interaction (or thread signaling). Pour plus d’informations, consultez la section interaction des threads ou signalisation de l’article vue d’ensemble des primitives de synchronisation .For more information, see the Thread interaction, or signaling section of the Overview of synchronization primitives article.

Lorsqu’un thread commence une activité qui doit se terminer avant que d’autres threads ne se poursuivent, ManualResetEvent il appelle ManualResetEvent. Reset pour mettre l’état non signalé.When a thread begins an activity that must complete before other threads proceed, it calls ManualResetEvent.Reset to put ManualResetEvent in the non-signaled state. Ce thread peut être considéré comme le ManualResetEventcontrôle de.This thread can be thought of as controlling the ManualResetEvent. Threads qui appellent le bloc ManualResetEvent. WaitOne , en attendant le signal.Threads that call ManualResetEvent.WaitOne block, awaiting the signal. Lorsque le thread de contrôle termine l’activité, il appelle ManualResetEvent. Set pour signaler que les threads en attente peuvent continuer.When the controlling thread completes the activity, it calls ManualResetEvent.Set to signal that the waiting threads can proceed. Tous les threads en attente sont libérés.All waiting threads are released.

Une fois qu’elle a été signalée, ManualResetEvent reste signalée jusqu’à ce qu’elle soit réinitialisée manuellement en appelant la Reset() méthode.Once it has been signaled, ManualResetEvent remains signaled until it is manually reset by calling the Reset() method. Autrement dit, les appels WaitOne à retournent immédiatement.That is, calls to WaitOne return immediately.

Vous pouvez contrôler l’état initial d’un ManualResetEvent en passant une valeur booléenne au constructeur: true si l’état initial est signalé, et false dans le cas contraire.You can control the initial state of a ManualResetEvent by passing a Boolean value to the constructor: true if the initial state is signaled, and false otherwise.

ManualResetEventpeut également être utilisé avec les static WaitAll méthodes WaitAny et.ManualResetEvent can also be used with the static WaitAll and WaitAny methods.

À partir de la version 2,0 de ManualResetEvent .NET Framework, dérive EventWaitHandle de la classe.Beginning with the .NET Framework version 2.0, ManualResetEvent derives from the EventWaitHandle class. Un ManualResetEvent est fonctionnellement équivalent à un EventWaitHandle créé avec EventResetMode.ManualReset.A ManualResetEvent is functionally equivalent to an EventWaitHandle created with EventResetMode.ManualReset.

Notes

Contrairement à ManualResetEvent la classe, EventWaitHandle la classe fournit l’accès aux événements de synchronisation système nommés.Unlike the ManualResetEvent class, the EventWaitHandle class provides access to named system synchronization events.

À partir de la version 4,0 de .NET Framework System.Threading.ManualResetEventSlim , la classe est une alternative ManualResetEventlégère à.Beginning with the .NET Framework version 4.0, the System.Threading.ManualResetEventSlim class is a lightweight alternative to ManualResetEvent.

Constructeurs

ManualResetEvent(Boolean) ManualResetEvent(Boolean) ManualResetEvent(Boolean) ManualResetEvent(Boolean)

Initialise une nouvelle instance de la classe ManualResetEvent avec une valeur booléenne indiquant si l'état initial doit être défini comme signalé.Initializes a new instance of the ManualResetEvent class with a Boolean value indicating whether to set the initial state to signaled.

Méthodes

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

Libère toutes les ressources détenues par le WaitHandle actuel.Releases all resources held by the current WaitHandle.

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

Crée un objet contenant toutes les informations appropriées requises pour générer un proxy permettant de communiquer avec un objet distant.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()

Libère toutes les ressources utilisées par l'instance actuelle de la classe WaitHandle.Releases all resources used by the current instance of the WaitHandle class.

(Inherited from WaitHandle)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

En cas de substitution dans une classe dérivée, libère les ressources non managées utilisées par WaitHandle et libère éventuellement les ressources managées.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)

Détermine si l'objet spécifié est identique à l'objet actuel.Determines whether the specified object is equal to the current object.

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

Fait office de fonction de hachage par défaut.Serves as the default hash function.

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

Récupère l'objet de service de durée de vie en cours qui contrôle la stratégie de durée de vie de cette instance.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

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

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

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

Obtient un objet de service de durée de vie pour contrôler la stratégie de durée de vie de cette instance.Obtains a lifetime service object to control the lifetime policy for this instance.

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

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

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

Crée une copie superficielle de l'objet MarshalByRefObject actuel.Creates a shallow copy of the current MarshalByRefObject object.

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

Définit l'état de l'événement à "non signalé", ce qui entraîne le blocage des threads.Sets the state of the event to nonsignaled, which causes threads to block.

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

Définit l'état de l'événement comme étant signalé, ce qui permet à un ou plusieurs threads en attente de continuer.Sets the state of the event to signaled, which allows one or more waiting threads to proceed.

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

Retourne une chaîne qui représente l'objet actuel.Returns a string that represents the current object.

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

Bloque le thread actuel jusqu'à ce que le WaitHandle actuel reçoive un signal.Blocks the current thread until the current WaitHandle receives a signal.

(Inherited from WaitHandle)
WaitOne(Int32) WaitOne(Int32) WaitOne(Int32) WaitOne(Int32)

Bloque le thread actuel jusqu'à ce que le WaitHandle actuel reçoive un signal, en utilisant un entier signé 32 bits pour spécifier l'intervalle de temps.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)

Bloque le thread actuel jusqu’à ce que le WaitHandle actuel reçoive un signal, en utilisant un entier signé 32 bits pour spécifier l’intervalle de temps et en spécifiant s’il faut quitter le domaine de synchronisation avant l’attente.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)

Bloque le thread actuel jusqu'à ce que l'instance actuelle reçoive un signal, en utilisant une valeur TimeSpan pour spécifier l'intervalle de temps.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)

Bloque le thread actuel jusqu'à ce que l'instance actuelle reçoive un signal, en utilisant une valeur TimeSpan pour spécifier l'intervalle de temps et en spécifiant s'il faut quitter le domaine de synchronisation avant l'attente.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)

Propriétés

Handle Handle Handle Handle

Obtient ou définit le handle du système d'exploitation natif.Gets or sets the native operating system handle.

(Inherited from WaitHandle)
SafeWaitHandle SafeWaitHandle SafeWaitHandle SafeWaitHandle

Obtient ou définit le handle du système d'exploitation natif.Gets or sets the native operating system handle.

(Inherited from WaitHandle)

Implémentations d’interfaces explicites

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

Libère toutes les ressources utilisées par WaitHandle.Releases all resources used by the WaitHandle.

(Inherited from WaitHandle)

Champs

WaitTimeout WaitTimeout WaitTimeout WaitTimeout

Indique que le délai fixé pour une opération WaitAny(WaitHandle[], Int32, Boolean) a été dépassé sans qu'aucun des handles d'attente n'ait été signalé.Indicates that a WaitAny(WaitHandle[], Int32, Boolean) operation timed out before any of the wait handles were signaled. Ce champ est constant.This field is constant.

(Inherited from WaitHandle)

Méthodes d’extension

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

Obtient le handle sécurisé pour un handle d’attente de système d’exploitation natif.Gets the safe handle for a native operating system wait handle.

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

Définit un handle sécurisé pour un handle d’attente de système d’exploitation natif.Sets a safe handle for a native operating system wait handle.

S’applique à

Cohérence de thread

Cette classe est thread-safe.This class is thread safe.

Voir aussi