Condividi tramite


AutoResetEvent Classe

Definizione

Rappresenta un evento di sincronizzazione thread che, quando segnalato, rilascia un singolo thread in attesa e quindi reimposta automaticamente. Questa 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 metodo Set (nella classe base) ogni volta che l'utente preme il tasto Invio. L'esempio avvia tre thread, che attendono un AutoResetEvent creato nello stato segnalato. Il primo thread viene rilasciato immediatamente, perché il AutoResetEvent è già nello stato segnalato. In questo modo il AutoResetEvent viene reimpostato sullo stato non segnalato, in modo che i thread successivi si blocchino. I thread bloccati non vengono rilasciati finché l'utente non li rilascia uno alla volta premendo il tasto Invio.

Dopo il rilascio dei thread dal primo AutoResetEvent, attende un altro AutoResetEvent creato nello stato non segnalato. Tutti e tre i thread bloccano, quindi il metodo Set 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 il AutoResetEvent è nello stato non segnalato, il thread si blocca fino a quando non viene chiamato il AutoResetEvent.Set. La chiamata di Set segnala AutoResetEvent di rilasciare un thread in attesa. AutoResetEvent rimane segnalato fino a quando non viene chiamato Reset o viene rilasciato un singolo thread in attesa, in cui torna automaticamente allo stato non segnalato.

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

Importante

Non esiste alcuna garanzia che ogni chiamata al metodo Set 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 il AutoResetEvent è già segnalato, la chiamata non ha alcun effetto.

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

AutoResetEvent possono essere usati anche con i metodi staticWaitAll e WaitAny.

AutoResetEvent deriva dalla classe EventWaitHandle. Un AutoResetEvent equivale funzionalmente a un EventWaitHandle creato con EventResetMode.AutoReset.

Nota

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

Importante

Questo tipo implementa l'interfaccia IDisposable. Al termine dell'uso del tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il metodo Dispose in un blocco try/catch. Per eliminarlo indirettamente, usare un costrutto del linguaggio, 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)

Inizializza una nuova istanza della classe AutoResetEvent con un valore booleano che indica se impostare lo stato iniziale su segnalato.

Campi

WaitTimeout

Indica che si è verificato un timeout di un'operazione WaitAny(WaitHandle[], Int32, Boolean) prima che uno degli handle di attesa sia stato segnalato. 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 nel WaitHandlecorrente.

(Ereditato da WaitHandle)
CreateObjRef(Type)

Crea un oggetto che contiene tutte le informazioni pertinenti necessarie per generare un proxy utilizzato per comunicare 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, rilascia le risorse non gestite usate dal WaitHandlee, facoltativamente, rilascia 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.

Recupera l'oggetto servizio di durata corrente che controlla i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene il 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 del Objectcorrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia superficiale dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
Reset()

Imposta lo stato dell'evento su non firmato, che causa il blocco dei thread.

Reset()

Imposta lo stato dell'evento su non firmato, causando il blocco dei thread.

(Ereditato da EventWaitHandle)
Set()

Imposta lo stato dell'evento su segnalato, che consente al massimo un thread in attesa di continuare.

Set()

Imposta lo stato dell'evento su segnalato, consentendo l'esecuzione di uno o più thread in attesa.

(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 fino a quando il WaitHandle corrente non riceve un segnale.

(Ereditato da WaitHandle)
WaitOne(Int32)

Blocca il thread corrente fino a quando il WaitHandle corrente non riceve un segnale, usando un intero con segno a 32 bit per specificare l'intervallo di tempo in millisecondi.

(Ereditato da WaitHandle)
WaitOne(Int32, Boolean)

Blocca il thread corrente fino a quando il WaitHandle corrente non riceve un segnale, utilizzando un intero con segno a 32 bit per specificare l'intervallo di tempo e specificando se uscire dal dominio di sincronizzazione prima dell'attesa.

(Ereditato da WaitHandle)
WaitOne(TimeSpan)

Blocca il thread corrente fino a quando l'istanza corrente non riceve un segnale, usando un TimeSpan per specificare l'intervallo di tempo.

(Ereditato da WaitHandle)
WaitOne(TimeSpan, Boolean)

Blocca il thread corrente fino a quando l'istanza corrente non riceve un segnale, usando un TimeSpan per specificare l'intervallo di tempo e specificando 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 dal WaitHandle.

(Ereditato da WaitHandle)

Metodi di estensione

GetAccessControl(EventWaitHandle)

Restituisce i descrittori di sicurezza per il handlespecificato.

SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)

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

GetSafeWaitHandle(WaitHandle)

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

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

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

Si applica a

Thread safety

Questa classe è thread-safe.

Vedi anche