AutoResetEvent Classe

Definizione

Rappresenta un evento di sincronizzazione thread che, quando segnalato, rilascia un singolo thread in attesa e quindi reimposta automaticamente. La classe non può essere ereditata.

public ref class AutoResetEvent sealed : System::Threading::EventWaitHandle
public ref class AutoResetEvent sealed : System::Threading::WaitHandle
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
public sealed class AutoResetEvent : System.Threading.WaitHandle
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
type AutoResetEvent = class
    inherit EventWaitHandle
type AutoResetEvent = class
    inherit WaitHandle
[<System.Runtime.InteropServices.ComVisible(true)>]
type AutoResetEvent = class
    inherit EventWaitHandle
Public NotInheritable Class AutoResetEvent
Inherits EventWaitHandle
Public NotInheritable Class AutoResetEvent
Inherits WaitHandle
Ereditarietà
Ereditarietà
Ereditarietà
Attributi

Esempio

Nell'esempio seguente viene illustrato come usare AutoResetEvent per rilasciare un thread alla volta chiamando il Set metodo (nella classe di base) ogni volta che l'utente preme il tasto INVIO . L'esempio avvia tre thread, che attendono un AutoResetEvent oggetto creato nello stato segnalato. Il primo thread viene rilasciato immediatamente, perché è AutoResetEvent già nello stato segnalato. In questo modo viene reimpostato lo AutoResetEvent stato non segnalato, in modo che i thread successivi blocchino. I thread bloccati non vengono rilasciati finché l'utente non li rilascia uno alla volta premendo INVIO .

Dopo il rilascio dei thread dalla prima AutoResetEvent, attende un altro AutoResetEvent che è stato creato nello stato non segnalato. Tutti e tre i thread vengono bloccati, quindi il Set metodo deve essere chiamato tre volte per rilasciarli tutti.

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.

Commenti

Si usano AutoResetEvent, ManualResetEvente EventWaitHandle per l'interazione tra thread (o segnalazione di thread). Per altre informazioni, vedere Interazione tra thread.

Un thread attende un segnale chiamando AutoResetEvent.WaitOne. Se è AutoResetEvent nello stato non segnalato, il thread si blocca finché non viene chiamato AutoResetEvent.Set . Chiamata di Set segnali AutoResetEvent per rilasciare un thread in attesa. AutoResetEvent rimane segnalato fino a quando Reset non viene chiamato o viene rilasciato un singolo thread in attesa, al momento in cui torna automaticamente allo stato non segnalato.

Se nessun thread è in attesa quando passa AutoResetEvent a uno stato segnalato, lo stato rimane segnalato fino a quando un thread non osserva il segnale (chiamando WaitOne). Il thread non viene bloccato: rilascia AutoResetEvent immediatamente il thread e torna allo stato non segnalato.

Importante

Non esiste alcuna garanzia che ogni chiamata al Set metodo rilasci un thread. Se due chiamate sono troppo vicine, in modo che la seconda chiamata venga eseguita prima del rilascio di un thread, viene rilasciato un solo thread. È come se la seconda chiamata non fosse stata eseguita. Inoltre, se Set viene chiamato quando non sono presenti thread in attesa e l'oggetto AutoResetEvent è già segnalato, la chiamata non ha alcun effetto.

È possibile controllare lo stato iniziale di un AutoResetEvent oggetto passando un valore booleano al costruttore: true se lo stato iniziale viene segnalato e in false caso contrario.

AutoResetEvent può essere usato anche con i staticWaitAll metodi e WaitAny .

AutoResetEvent deriva dalla EventWaitHandle classe . Un AutoResetEvent oggetto è equivalente funzionalmente a un EventWaitHandle oggetto creato con EventResetMode.AutoReset.

Nota

A differenza della AutoResetEvent classe , la EventWaitHandle classe fornisce l'accesso agli eventi di sincronizzazione del sistema denominati.

Importante

Il tipo implementa l'interfaccia IDisposable. Dopo aver utilizzato il tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il metodo Dispose in un blocco try/catch. Per eliminarlo indirettamente, utilizzare un costrutto di linguaggio come ad esempio using in C# o Using in Visual Basic. Per altre informazioni, vedere la sezione "Uso di un oggetto che implementa IDisposable" nella pagina dell'interfaccia IDisposable .

Costruttori

AutoResetEvent(Boolean)

Consente l'inizializzazione di una nuova istanza della classe AutoResetEvent con un valore Booleano che indica se lo stato iniziale deve essere impostato su segnalato.

Campi

WaitTimeout

Indica che si è verificato il timeout di un'operazione WaitAny(WaitHandle[], Int32, Boolean) prima della segnalazione di uno degli handle di attesa. Questo campo è costante.

(Ereditato da WaitHandle)

Proprietà

Handle
Obsoleti.
Obsoleti.

Ottiene o imposta l'handle nativo del sistema operativo.

(Ereditato da WaitHandle)
SafeWaitHandle

Ottiene o imposta l'handle nativo del sistema operativo.

(Ereditato da WaitHandle)

Metodi

Close()

Rilascia tutte le risorse contenute nell'oggetto WaitHandle corrente.

(Ereditato da WaitHandle)
CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
Dispose()

Rilascia tutte le risorse usate dall'istanza corrente della classe WaitHandle.

(Ereditato da WaitHandle)
Dispose(Boolean)

Quando ne viene eseguito l'override in una classe derivata, libera le risorse non gestite usate da WaitHandle ed eventualmente di liberare le risorse gestite.

(Ereditato da WaitHandle)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetAccessControl()

Ottiene un oggetto EventWaitHandleSecurity che rappresenta la sicurezza del controllo di accesso per l'evento di sistema denominato rappresentato dall'oggetto EventWaitHandle corrente.

(Ereditato da EventWaitHandle)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleti.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
Reset()

Imposta lo stato dell'evento su non segnalato, provocando il blocco dei thread.

Reset()

Imposta lo stato dell'evento su non segnalato, provocando il blocco dei thread.

(Ereditato da EventWaitHandle)
Set()

Imposta lo stato dell'evento su segnalato, per consentire a un solo thread in attesa di procedere.

Set()

Imposta lo stato dell'evento su segnalato, per consentire a uno o più thread in attesa di procedere.

(Ereditato da EventWaitHandle)
SetAccessControl(EventWaitHandleSecurity)

Imposta la sicurezza del controllo di accesso per un evento di sistema denominato.

(Ereditato da EventWaitHandle)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
WaitOne()

Blocca il thread corrente finché l'oggetto WaitHandle corrente non riceve un segnale.

(Ereditato da WaitHandle)
WaitOne(Int32)

Blocca il thread corrente finché l'oggetto WaitHandle corrente non riceve un segnale, usando un intero con segno a 32 bit per specificare l'intervallo di tempo.

(Ereditato da WaitHandle)
WaitOne(Int32, Boolean)

Blocca il thread corrente finché l'oggetto WaitHandle corrente non riceve un segnale, usando un intero con segno a 32 bit per specificare l'intervallo di tempo e indicando se uscire dal dominio di sincronizzazione prima dell'attesa.

(Ereditato da WaitHandle)
WaitOne(TimeSpan)

Blocca il thread corrente finché l'istanza corrente non riceve un segnale, usando un valore TimeSpan per specificare l'intervallo di tempo.

(Ereditato da WaitHandle)
WaitOne(TimeSpan, Boolean)

Blocca il thread corrente finché l'istanza corrente non riceve un segnale, usando un oggetto TimeSpan per specificare l'intervallo di tempo e indicando se uscire dal dominio di sincronizzazione prima dell'attesa.

(Ereditato da WaitHandle)

Implementazioni dell'interfaccia esplicita

IDisposable.Dispose()

Questa API supporta l'infrastruttura del prodotto e non è previsto che venga usata direttamente dal codice.

Rilascia tutte le risorse usate da WaitHandle.

(Ereditato da WaitHandle)

Metodi di estensione

GetAccessControl(EventWaitHandle)

Restituisce i descrittori di sicurezza per l'oggetto handle specificato.

SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)

Imposta i descrittori di sicurezza per l'handle di attesa evento specificato.

GetSafeWaitHandle(WaitHandle)

Ottiene l'handle sicuro per un handle di attesa nativo del sistema operativo.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Imposta un handle sicuro per un handle di attesa nativo del sistema operativo.

Si applica a

Thread safety

Questa classe è thread-safe.

Vedi anche