語言

CountdownEvent 類別

定義

表示當同步處理基本類型計數達到零時發出訊號。

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
繼承
CountdownEvent
屬性
實作

範例

以下範例展示了如何使用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

建構函式

名稱 Description
CountdownEvent(Int32)

初始化一個以指定計數的新類別實例 CountdownEvent 。

屬性

名稱 Description
CurrentCount

取得設定事件所需的剩餘訊號數量。

InitialCount

取得設定事件所需的訊號數量。

IsSet

表示物件目前的計數是否 CountdownEvent 已歸零。

WaitHandle

會拿到 WaitHandle 一個用來等待事件設定的。

方法

名稱 Description
AddCount()

將 CountdownEvent的當前計數增加一。

AddCount(Int32)

將 CountdownEvent的當前計數增加指定值。

Dispose()

釋放目前類別實例 CountdownEvent 所使用的所有資源。

Dispose(Boolean)

釋放 所使用的 CountdownEvent未管理資源,並可選擇性地釋放受管理資源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type。

(繼承來源 Object)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
Reset()

將 重置 CurrentCount 為 的 InitialCount值。

Reset(Int32)

將屬性 InitialCount 重置為指定值。

Signal()

將訊號註冊為 CountdownEvent,遞減 的 CurrentCount值。

Signal(Int32)

以 註冊多個訊號 CountdownEvent,並將 的 CurrentCount 值遞減至指定數量。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)
TryAddCount()

嘗試增加一分 CurrentCount 。

TryAddCount(Int32)

嘗試以指定值遞 CurrentCount 增。

Wait()

阻塞目前執行緒直到設定 CountdownEvent 完成。

Wait(CancellationToken)

在觀察 一個 CountdownEvent時,阻塞當前執行緒直到 被CancellationToken設定為止。

Wait(Int32, CancellationToken)

會阻塞目前執行緒直到設定完成,CountdownEvent並使用一個 32 位元的有符號整數來測量逾時,同時觀察 。CancellationToken

Wait(Int32)

會阻塞目前執行緒直到設定完成, CountdownEvent 並使用 32 位元有符號整數來測量逾時。

Wait(TimeSpan, CancellationToken)

在設定 之前阻塞目前執行緒 CountdownEvent ,並使用 a TimeSpan 來測量逾時,同時觀察 CancellationToken。

Wait(TimeSpan)

阻塞目前執行緒直到設定 CountdownEvent 完成,並使用 a TimeSpan 來測量逾時。

適用於

執行緒安全性

所有公開且受保護的成員 CountdownEvent 皆為執行緒安全,且可同時從多個執行緒使用,唯獨 Dispose(),該 必須在所有其他操作 CountdownEvent 完成後使用,且 Reset()僅在無其他執行緒存取該事件時使用。

另請參閱