CountdownEvent Classe

Definizione

Rappresenta una primitiva di sincronizzazione segnalata quando il conteggio raggiunge zero.

public ref class CountdownEvent : IDisposable
public class CountdownEvent : IDisposable
[System.Runtime.InteropServices.ComVisible(false)]
public class CountdownEvent : IDisposable
type CountdownEvent = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(false)>]
type CountdownEvent = class
    interface IDisposable
Public Class CountdownEvent
Implements IDisposable
Ereditarietà
CountdownEvent
Attributi
Implementazioni

Esempio

Nell'esempio seguente viene illustrato come usare un oggetto CountdownEvent:

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Example
{
    static async Task Main()
    {
        // Initialize a queue and a CountdownEvent
        ConcurrentQueue<int> queue = new ConcurrentQueue<int>(Enumerable.Range(0, 10000));
        CountdownEvent cde = new CountdownEvent(10000); // initial count = 10000

        // This is the logic for all queue consumers
        Action consumer = () =>
        {
            int local;
            // decrement CDE count once for each element consumed from queue
            while (queue.TryDequeue(out local)) cde.Signal();
        };

        // Now empty the queue with a couple of asynchronous tasks
        Task t1 = Task.Factory.StartNew(consumer);
        Task t2 = Task.Factory.StartNew(consumer);

        // And wait for queue to empty by waiting on cde
        cde.Wait(); // will return when cde count reaches 0

        Console.WriteLine("Done emptying queue.  InitialCount={0}, CurrentCount={1}, IsSet={2}",
            cde.InitialCount, cde.CurrentCount, cde.IsSet);

        // Proper form is to wait for the tasks to complete, even if you know that their work
        // is done already.
        await Task.WhenAll(t1, t2);

        // Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount
        // to the specified value
        cde.Reset(10);

        // AddCount will affect the CurrentCount, but not the InitialCount
        cde.AddCount(2);

        Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}",
            cde.InitialCount, cde.CurrentCount, cde.IsSet);

        // Now try waiting with cancellation
        CancellationTokenSource cts = new CancellationTokenSource();
        cts.Cancel(); // cancels the CancellationTokenSource
        try
        {
            cde.Wait(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected");
        }
        finally
        {
           cts.Dispose();
        }
        // It's good to release a CountdownEvent when you're done with it.
        cde.Dispose();
    }
}
// The example displays the following output:
//    Done emptying queue.  InitialCount=10000, CurrentCount=0, IsSet=True
//    After Reset(10), AddCount(2): InitialCount=10, CurrentCount=12, IsSet=False
//    cde.Wait(preCanceledToken) threw OCE, as expected
Imports System.Collections.Concurrent
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks

Module Example
    Sub Main()
        ' Initialize a queue and a CountdownEvent
        Dim queue As New ConcurrentQueue(Of Integer)(Enumerable.Range(0, 10000))
        Dim cde As New CountdownEvent(10000)
        ' initial count = 10000
        ' This is the logic for all queue consumers
        Dim consumer As Action =
            Sub()
                Dim local As Integer
                ' decrement CDE count once for each element consumed from queue
                While queue.TryDequeue(local)
                    cde.Signal()
                End While
            End Sub

        ' Now empty the queue with a couple of asynchronous tasks
        Dim t1 As Task = Task.Factory.StartNew(consumer)
        Dim t2 As Task = Task.Factory.StartNew(consumer)

        ' And wait for queue to empty by waiting on cde
        cde.Wait()
        ' will return when cde count reaches 0
        Console.WriteLine("Done emptying queue. InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet)

        ' Proper form is to wait for the tasks to complete, even if you know that their work
        ' is done already.
        Task.WaitAll(t1, t2)

        ' Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount
        ' to the specified value
        cde.Reset(10)

        ' AddCount will affect the CurrentCount, but not the InitialCount
        cde.AddCount(2)

        Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet)

        ' Now try waiting with cancellation
        Dim cts As New CancellationTokenSource()
        cts.Cancel()
        ' cancels the CancellationTokenSource
        Try
            cde.Wait(cts.Token)
        Catch generatedExceptionName As OperationCanceledException
            Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected")
        Finally
           cts.Dispose()
        End Try

        ' It's good to release a CountdownEvent when you're done with it.
        cde.Dispose()
    End Sub
End Module
' The example displays the following output:
'    Done emptying queue.  InitialCount=10000, CurrentCount=0, IsSet=True
'    After Reset(10), AddCount(2): InitialCount=10, CurrentCount=12, IsSet=False
'    cde.Wait(preCanceledToken) threw OCE, as expected

Costruttori

Nome Descrizione
CountdownEvent(Int32)

Inizializza una nuova istanza della CountdownEvent classe con il conteggio specificato.

Proprietà

Nome Descrizione
CurrentCount

Ottiene il numero di segnali rimanenti necessari per impostare l'evento.

InitialCount

Ottiene il numero di segnali inizialmente necessari per impostare l'evento.

IsSet

Indica se il CountdownEvent conteggio corrente dell'oggetto è stato raggiunto zero.

WaitHandle

Ottiene un WaitHandle oggetto utilizzato per attendere l'impostazione dell'evento.

Metodi

Nome Descrizione
AddCount()

Incrementa il CountdownEventconteggio corrente di uno.

AddCount(Int32)

Incrementa il CountdownEventconteggio corrente di un valore specificato.

Dispose()

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

Dispose(Boolean)

Rilascia le risorse non gestite usate da CountdownEvente, facoltativamente, rilascia le risorse gestite.

Equals(Object)

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

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
Reset()

Reimposta il CurrentCount valore di InitialCount.

Reset(Int32)

Reimposta la InitialCount proprietà su un valore specificato.

Signal()

Registra un segnale con , CountdownEventdecrementando il valore di CurrentCount.

Signal(Int32)

Registra più segnali con , CountdownEventdecrementando il valore di in CurrentCount base all'importo specificato.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
TryAddCount()

Tenta di incrementare CurrentCount di uno.

TryAddCount(Int32)

Tenta di incrementare CurrentCount in base a un valore specificato.

Wait()

Blocca il thread corrente fino a quando non viene impostato .CountdownEvent

Wait(CancellationToken)

Blocca il thread corrente fino a quando non CountdownEvent viene impostato , osservando un oggetto CancellationToken.

Wait(Int32, CancellationToken)

Blocca il thread corrente fino a quando non CountdownEvent viene impostato, usando un intero con segno a 32 bit per misurare il timeout, osservando un oggetto CancellationToken.

Wait(Int32)

Blocca il thread corrente fino a quando non CountdownEvent viene impostato, utilizzando un intero con segno a 32 bit per misurare il timeout.

Wait(TimeSpan, CancellationToken)

Blocca il thread corrente fino a quando non CountdownEvent viene impostato, utilizzando un TimeSpan oggetto per misurare il timeout, osservando un oggetto CancellationToken.

Wait(TimeSpan)

Blocca il thread corrente fino a quando non CountdownEvent viene impostato, utilizzando un TimeSpan oggetto per misurare il timeout.

Si applica a

Thread safety

Tutti i membri pubblici e protetti di CountdownEvent sono thread-safe e possono essere usati simultaneamente da più thread, ad eccezione di Dispose(), che devono essere usati solo quando tutte le altre operazioni sull'oggetto CountdownEvent sono state completate e Reset(), che devono essere usate solo quando nessun altro thread accede all'evento.

Vedi anche