BlockingCollection<T> BlockingCollection<T> BlockingCollection<T> BlockingCollection<T> Class

定義

提供安全執行緒集合適用的封鎖和界限容量,這個集合會實作 IProducerConsumerCollection<T>Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.

generic <typename T>
public ref class BlockingCollection : IDisposable, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
[System.Runtime.InteropServices.ComVisible(false)]
public class BlockingCollection<T> : IDisposable, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
type BlockingCollection<'T> = class
    interface seq<'T>
    interface ICollection
    interface IDisposable
    interface IReadOnlyCollection<'T>
    interface IEnumerable
Public Class BlockingCollection(Of T)
Implements ICollection, IDisposable, IEnumerable(Of T), IReadOnlyCollection(Of T)

類型參數

T

集合中項目的類型。The type of elements in the collection.

繼承
BlockingCollection<T>BlockingCollection<T>BlockingCollection<T>BlockingCollection<T>
屬性
實作

範例

下列範例示範如何新增和擷取封鎖回收中同時的項目:The following example shows how to add and take items concurrently from a blocking collection:

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

class BlockingCollectionDemo
{
    static async Task Main()
    {
        await AddTakeDemo.BC_AddTakeCompleteAdding();
        TryTakeDemo.BC_TryTake();
        FromToAnyDemo.BC_FromToAny();
        await ConsumingEnumerableDemo.BC_GetConsumingEnumerable();
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
class AddTakeDemo
{
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.Take()
    //      BlockingCollection<T>.CompleteAdding()
    public static async Task BC_AddTakeCompleteAdding()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {
            // Spin up a Task to populate the BlockingCollection
            using (Task t1 = Task.Run(() =>
            {
                bc.Add(1);
                bc.Add(2);
                bc.Add(3);
                bc.CompleteAdding();
            }))
            {
                // Spin up a Task to consume the BlockingCollection
                using (Task t2 = Task.Run(() =>
                {
                    try
                    {
                        // Consume consume the BlockingCollection
                        while (true) Console.WriteLine(bc.Take());
                    }
                    catch (InvalidOperationException)
                    {
                        // An InvalidOperationException means that Take() was called on a completed collection
                        Console.WriteLine("That's All!");
                    }
                }))
                {
                    await Task.WhenAll(t1, t2);
                }
            }
        }
    }
}

class TryTakeDemo
{
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.TryTake()
    //      BlockingCollection<T>.IsCompleted
    public static void BC_TryTake()
    {
        // Construct and fill our BlockingCollection
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {
            int NUMITEMS = 10000;
            for (int i = 0; i < NUMITEMS; i++) bc.Add(i);
            bc.CompleteAdding();
            int outerSum = 0;

            // Delegate for consuming the BlockingCollection and adding up all items
            Action action = () =>
            {
                int localItem;
                int localSum = 0;

                while (bc.TryTake(out localItem)) localSum += localItem;
                Interlocked.Add(ref outerSum, localSum);
            };

            // Launch three parallel actions to consume the BlockingCollection
            Parallel.Invoke(action, action, action);

            Console.WriteLine("Sum[0..{0}) = {1}, should be {2}", NUMITEMS, outerSum, ((NUMITEMS * (NUMITEMS - 1)) / 2));
            Console.WriteLine("bc.IsCompleted = {0} (should be true)", bc.IsCompleted);
        }
    }
}

class FromToAnyDemo
{
    // Demonstrates:
    //      Bounded BlockingCollection<T>
    //      BlockingCollection<T>.TryAddToAny()
    //      BlockingCollection<T>.TryTakeFromAny()
    public static void BC_FromToAny()
    {
        BlockingCollection<int>[] bcs = new BlockingCollection<int>[2];
        bcs[0] = new BlockingCollection<int>(5); // collection bounded to 5 items
        bcs[1] = new BlockingCollection<int>(5); // collection bounded to 5 items

        // Should be able to add 10 items w/o blocking
        int numFailures = 0;
        for (int i = 0; i < 10; i++)
        {
            if (BlockingCollection<int>.TryAddToAny(bcs, i) == -1) numFailures++;
        }
        Console.WriteLine("TryAddToAny: {0} failures (should be 0)", numFailures);

        // Should be able to retrieve 10 items
        int numItems = 0;
        int item;
        while (BlockingCollection<int>.TryTakeFromAny(bcs, out item) != -1) numItems++;
        Console.WriteLine("TryTakeFromAny: retrieved {0} items (should be 10)", numItems);
    }
}

class ConsumingEnumerableDemo
{
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.GetConsumingEnumerable()
    public static async Task BC_GetConsumingEnumerable()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {
            // Kick off a producer task
            await Task.Run(async () =>
            {
                for (int i = 0; i < 10; i++)
                {
                    bc.Add(i);
                    await Task.Delay(100); // sleep 100 ms between adds
                }

                // Need to do this to keep foreach below from hanging
                bc.CompleteAdding();
            });

            // Now consume the blocking collection with foreach.
            // Use bc.GetConsumingEnumerable() instead of just bc because the
            // former will block waiting for completion and the latter will
            // simply take a snapshot of the current state of the underlying collection.
            foreach (var item in bc.GetConsumingEnumerable())
            {
                Console.WriteLine(item);
            }
        }
    }
}
Imports System.Threading.Tasks
Imports System.Collections.Concurrent
Imports System.Threading

Class BlockingCollectionDemo
    Shared Sub Main()
        AddTakeDemo.BC_AddTakeCompleteAdding()
        TryTakeDemo.BC_TryTake()
        ToAnyDemo.BC_ToAny()
        ConsumingEnumerableDemo.BC_GetConsumingEnumerable()
        ' Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub
End Class

Class AddTakeDemo

    ' Demonstrates:
    ' BlockingCollection<T>.Add()
    ' BlockingCollection<T>.Take()
    ' BlockingCollection<T>.CompleteAdding()
    Shared Sub BC_AddTakeCompleteAdding()
        Using bc As New BlockingCollection(Of Integer)()

            ' Spin up a Task to populate the BlockingCollection 
            Using t1 As Task = Task.Factory.StartNew(
                Sub()
                    bc.Add(1)
                    bc.Add(2)
                    bc.Add(3)
                    bc.CompleteAdding()
                End Sub)
                ' Spin up a Task to consume the BlockingCollection
                Using t2 As Task = Task.Factory.StartNew(
                Sub()
                    Try
                        ' Consume the BlockingCollection
                        While True
                            Console.WriteLine(bc.Take())
                        End While
                    Catch generatedExceptionName As InvalidOperationException
                        ' An InvalidOperationException means that Take() was called on a completed collection
                        Console.WriteLine("That's All!")
                    End Try
                End Sub)

                    Task.WaitAll(t1, t2)
                End Using
            End Using
        End Using
    End Sub



End Class

'Imports System.Collections.Concurrent
' Imports System.Threading
'Imports System.Threading.Tasks

Class TryTakeDemo
    ' Demonstrates:
    ' BlockingCollection<T>.Add()
    ' BlockingCollection<T>.CompleteAdding()
    ' BlockingCollection<T>.TryTake()
    ' BlockingCollection<T>.IsCompleted
    Shared Sub BC_TryTake()
        ' Construct and fill our BlockingCollection
        Using bc As New BlockingCollection(Of Integer)()
            Dim NUMITEMS As Integer = 10000
            For i As Integer = 0 To NUMITEMS - 1
                bc.Add(i)
            Next
            bc.CompleteAdding()
            Dim outerSum As Integer = 0

            ' Delegate for consuming the BlockingCollection and adding up all items
            Dim action As Action =
                Sub()
                    Dim localItem As Integer
                    Dim localSum As Integer = 0

                    While bc.TryTake(localItem)
                        localSum += localItem
                    End While
                    Interlocked.Add(outerSum, localSum)
                End Sub

            ' Launch three parallel actions to consume the BlockingCollection
            Parallel.Invoke(action, action, action)

            Console.WriteLine("Sum[0..{0}) = {1}, should be {2}", NUMITEMS, outerSum, ((NUMITEMS * (NUMITEMS - 1)) / 2))
            Console.WriteLine("bc.IsCompleted = {0} (should be true)", bc.IsCompleted)
        End Using
    End Sub

End Class

'Imports System.Threading.Tasks
'Imports System.Collections.Concurrent

' Demonstrates:
' Bounded BlockingCollection<T>
' BlockingCollection<T>.TryAddToAny()
' BlockingCollection<T>.TryTakeFromAny()
Class ToAnyDemo
    Shared Sub BC_ToAny()
        Dim bcs As BlockingCollection(Of Integer)() = New BlockingCollection(Of Integer)(1) {}
        bcs(0) = New BlockingCollection(Of Integer)(5)
        ' collection bounded to 5 items
        bcs(1) = New BlockingCollection(Of Integer)(5)
        ' collection bounded to 5 items
        ' Should be able to add 10 items w/o blocking
        Dim numFailures As Integer = 0
        For i As Integer = 0 To 9
            If BlockingCollection(Of Integer).TryAddToAny(bcs, i) = -1 Then
                numFailures += 1
            End If
        Next
        Console.WriteLine("TryAddToAny: {0} failures (should be 0)", numFailures)

        ' Should be able to retrieve 10 items
        Dim numItems As Integer = 0
        Dim item As Integer
        While BlockingCollection(Of Integer).TryTakeFromAny(bcs, item) <> -1
            numItems += 1
        End While
        Console.WriteLine("TryTakeFromAny: retrieved {0} items (should be 10)", numItems)
    End Sub
End Class

'Imports System.Threading.Tasks
'Imports System.Collections.Concurrent

' Demonstrates:
' BlockingCollection<T>.Add()
' BlockingCollection<T>.CompleteAdding()
' BlockingCollection<T>.GetConsumingEnumerable()

Class ConsumingEnumerableDemo
    Shared Sub BC_GetConsumingEnumerable()
        Using bc As New BlockingCollection(Of Integer)()

            ' Kick off a producer task
            Task.Factory.StartNew(
                Sub()
                    For i As Integer = 0 To 9
                        bc.Add(i)
                        ' sleep 100 ms between adds
                        Thread.Sleep(100)
                    Next

                    ' Need to do this to keep foreach below from not responding.
                    bc.CompleteAdding()
                End Sub)
            ' Now consume the blocking collection with foreach.
            ' Use bc.GetConsumingEnumerable() instead of just bc because the
            ' former will block waiting for completion and the latter will
            ' simply take a snapshot of the current state of the underlying collection.
            For Each item In bc.GetConsumingEnumerable()
                Console.WriteLine(item)
            Next
        End Using
    End Sub
End Class

備註

BlockingCollection<T> 是安全執行緒集合類別,提供下列功能:BlockingCollection<T> is a thread-safe collection class that provides the following:

重要

此類型會實作IDisposable介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該處置它直接或間接。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,呼叫其Dispose方法中的try / catch區塊。To dispose of the type directly, call its Dispose method in a try/catch block. 若要處置它間接,使用的語言建構這類using(在 C# 中) 或Using(在 Visual Basic)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 「 使用物件,實作 IDisposable 」 一節IDisposable介面 > 主題。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic. 另請注意,Dispose()方法不是安全執行緒。Also, note that the Dispose() method is not thread-safe. 所有公用和受保護的其他成員BlockingCollection<T>是安全執行緒,且可能會從多個執行緒同時使用。All other public and protected members of BlockingCollection<T> are thread-safe and may be used concurrently from multiple threads.

IProducerConsumerCollection<T> 表示允許安全執行緒新增和移除資料的集合。IProducerConsumerCollection<T> represents a collection that allows for thread-safe adding and removal of data. BlockingCollection<T> 做為包裝函式IProducerConsumerCollection<T>執行個體,並允許將嘗試從集合移除封鎖,直到資料可被移除為止。BlockingCollection<T> is used as a wrapper for an IProducerConsumerCollection<T> instance, and allows removal attempts from the collection to block until data is available to be removed. 同樣地,您可以建立BlockingCollection<T>若要強制執行資料元素中允許的數目上限IProducerConsumerCollection<T>; 新增至集合的嘗試再封鎖,直到空間可用來儲存新增的項目。Similarly, you can create a BlockingCollection<T> to enforce an upper bound on the number of data elements allowed in the IProducerConsumerCollection<T>; addition attempts to the collection may then block until space is available to store the added items. 如此一來,在BlockingCollection<T>是傳統封鎖佇列的資料結構,類似,不同之處在於基礎資料儲存機制抽象化為IProducerConsumerCollection<T>In this manner, BlockingCollection<T> is similar to a traditional blocking queue data structure, except that the underlying data storage mechanism is abstracted away as an IProducerConsumerCollection<T>.

BlockingCollection<T> 支援界限和封鎖。BlockingCollection<T> supports bounding and blocking. 週框表示您可以設定集合的最大容量。Bounding means that you can set the maximum capacity of the collection. 週框是特定案例中很重要,因為它可讓您控制記憶體中集合的大小上限,而且它會防止產生執行緒移太遠之前使用的執行緒。多個執行緒或工作可以將項目加入集合,並產生的執行緒如果集合已達到其指定的最大容量,將會封鎖,直到移除項目。Bounding is important in certain scenarios because it enables you to control the maximum size of the collection in memory, and it prevents the producing threads from moving too far ahead of the consuming threads.Multiple threads or tasks can add items to the collection concurrently, and if the collection reaches its specified maximum capacity, the producing threads will block until an item is removed. 多位消費者可以同時移除項目,如果集合變成空的,則會在生產者新增項目之前封鎖使用執行緒。Multiple consumers can remove items concurrently, and if the collection becomes empty, the consuming threads will block until a producer adds an item. 產生執行緒可以呼叫CompleteAdding方法,以表示將會加入任何其他項目。A producing thread can call the CompleteAdding method to indicate that no more items will be added. 消費者會監視 IsCompleted 屬性,以得知集合何時變成空的,以及何時無法再新增項目。Consumers monitor the IsCompleted property to know when the collection is empty and no more items will be added.

AddTake作業通常會在迴圈中。Add and Take operations are typically performed in a loop. 您可以藉由傳入取消迴圈CancellationToken物件至TryAddTryTake方法,並核取的權杖值IsCancellationRequested每個反覆運算上的屬性。You can cancel a loop by passing in a CancellationToken object to the TryAdd or TryTake method, and then checking the value of the token's IsCancellationRequested property on each iteration. 如果值為true,它可以決定是否要清除任何資源並結束迴圈,以回應取消要求。If the value is true, it is up to you to respond the cancellation request by cleaning up any resources and exiting the loop.

當您建立BlockingCollection<T>物件,您可以指定界限的容量不僅集合型別使用。When you create a BlockingCollection<T> object, you can specify not only the bounded capacity but also the type of collection to use. 例如,您可以針對先進先出 (FIFO) 行為指定 ConcurrentQueue<T> 物件,或針對後進先出 (LIFO) 行為指定 ConcurrentStack<T> 物件。For example, you could specify a ConcurrentQueue<T> object for first in, first out (FIFO) behavior, or a ConcurrentStack<T> object for last in, first out (LIFO) behavior. 您可以使用任何可實作 IProducerConsumerCollection<T> 介面的集合類別。You can use any collection class that implements the IProducerConsumerCollection<T> interface. BlockingCollection<T> 的預設集合類型為 ConcurrentQueue<T>The default collection type for BlockingCollection<T> is ConcurrentQueue<T>.

請勿直接修改基礎集合。Do not modify the underlying collection directly. 使用BlockingCollection<T>方法來新增或移除項目。Use BlockingCollection<T> methods to add or remove elements. BlockingCollection<T>物件會損毀,如果您直接變更基礎的集合。The BlockingCollection<T> object can become corrupted if you change the underlying collection directly.

建構函式

BlockingCollection<T>() BlockingCollection<T>() BlockingCollection<T>() BlockingCollection<T>()

在無上限情況下,初始化 BlockingCollection<T> 類別的新執行個體。Initializes a new instance of the BlockingCollection<T> class without an upper-bound.

BlockingCollection<T>(Int32) BlockingCollection<T>(Int32) BlockingCollection<T>(Int32) BlockingCollection<T>(Int32)

在指定的上限情況下,初始化 BlockingCollection<T> 類別的新執行個體。Initializes a new instance of the BlockingCollection<T> class with the specified upper-bound.

BlockingCollection<T>(IProducerConsumerCollection<T>) BlockingCollection<T>(IProducerConsumerCollection<T>) BlockingCollection<T>(IProducerConsumerCollection<T>) BlockingCollection<T>(IProducerConsumerCollection<T>)

在無上限情況下,使用提供的 BlockingCollection<T> 做為類別之基礎資料存放區,初始化 IProducerConsumerCollection<T> 類別的新執行個體。Initializes a new instance of the BlockingCollection<T> class without an upper-bound and using the provided IProducerConsumerCollection<T> as its underlying data store.

BlockingCollection<T>(IProducerConsumerCollection<T>, Int32) BlockingCollection<T>(IProducerConsumerCollection<T>, Int32) BlockingCollection<T>(IProducerConsumerCollection<T>, Int32) BlockingCollection<T>(IProducerConsumerCollection<T>, Int32)

在指定上限情況下,使用提供的 BlockingCollection<T> 做為類別之基礎資料存放區,初始化 IProducerConsumerCollection<T> 類別的新執行個體。Initializes a new instance of the BlockingCollection<T> class with the specified upper-bound and using the provided IProducerConsumerCollection<T> as its underlying data store.

屬性

BoundedCapacity BoundedCapacity BoundedCapacity BoundedCapacity

取得這個 BlockingCollection<T> 執行個體的界限容量。Gets the bounded capacity of this BlockingCollection<T> instance.

Count Count Count Count

取得 BlockingCollection<T> 中所含的項目數。Gets the number of items contained in the BlockingCollection<T>.

IsAddingCompleted IsAddingCompleted IsAddingCompleted IsAddingCompleted

取得值,表示這個 BlockingCollection<T> 是否標記為加入完成。Gets whether this BlockingCollection<T> has been marked as complete for adding.

IsCompleted IsCompleted IsCompleted IsCompleted

取得值,表示這個 BlockingCollection<T> 是否標記為加入完成,而且是空的。Gets whether this BlockingCollection<T> has been marked as complete for adding and is empty.

方法

Add(T) Add(T) Add(T) Add(T)

將項目加入至 BlockingCollection<T>Adds the item to the BlockingCollection<T>.

Add(T, CancellationToken) Add(T, CancellationToken) Add(T, CancellationToken) Add(T, CancellationToken)

將項目加入至 BlockingCollection<T>Adds the item to the BlockingCollection<T>.

AddToAny(BlockingCollection<T>[], T) AddToAny(BlockingCollection<T>[], T) AddToAny(BlockingCollection<T>[], T) AddToAny(BlockingCollection<T>[], T)

將指定的項目加入至任何一個指定的 BlockingCollection<T> 執行個體。Adds the specified item to any one of the specified BlockingCollection<T> instances.

AddToAny(BlockingCollection<T>[], T, CancellationToken) AddToAny(BlockingCollection<T>[], T, CancellationToken) AddToAny(BlockingCollection<T>[], T, CancellationToken) AddToAny(BlockingCollection<T>[], T, CancellationToken)

將指定的項目加入至任何一個指定的 BlockingCollection<T> 執行個體。Adds the specified item to any one of the specified BlockingCollection<T> instances.

CompleteAdding() CompleteAdding() CompleteAdding() CompleteAdding()

BlockingCollection<T> 執行個體標記為不再接受任何加入項目。Marks the BlockingCollection<T> instances as not accepting any more additions.

CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32)

從目標陣列中的指定索引處開始,將 BlockingCollection<T> 執行個體中的所有項目複製到相容的一維陣列。Copies all of the items in the BlockingCollection<T> instance to a compatible one-dimensional array, starting at the specified index of the target array.

Dispose() Dispose() Dispose() Dispose()

釋放 BlockingCollection<T> 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the BlockingCollection<T> class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 BlockingCollection<T> 執行個體所使用的資源。Releases resources used by the BlockingCollection<T> instance.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetConsumingEnumerable() GetConsumingEnumerable() GetConsumingEnumerable() GetConsumingEnumerable()

提供集合中項目的耗用 IEnumerator<T>Provides a consuming IEnumerator<T> for items in the collection.

GetConsumingEnumerable(CancellationToken) GetConsumingEnumerable(CancellationToken) GetConsumingEnumerable(CancellationToken) GetConsumingEnumerable(CancellationToken)

提供集合中項目的耗用 IEnumerable<T>Provides a consuming IEnumerable<T> for items in the collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

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

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Take() Take() Take() Take()

BlockingCollection<T> 移除項目。Removes an item from the BlockingCollection<T>.

Take(CancellationToken) Take(CancellationToken) Take(CancellationToken) Take(CancellationToken)

BlockingCollection<T> 移除項目。Removes an item from the BlockingCollection<T>.

TakeFromAny(BlockingCollection<T>[], T) TakeFromAny(BlockingCollection<T>[], T) TakeFromAny(BlockingCollection<T>[], T) TakeFromAny(BlockingCollection<T>[], T)

從任何一個指定的 BlockingCollection<T> 執行個體取得項目。Takes an item from any one of the specified BlockingCollection<T> instances.

TakeFromAny(BlockingCollection<T>[], T, CancellationToken) TakeFromAny(BlockingCollection<T>[], T, CancellationToken) TakeFromAny(BlockingCollection<T>[], T, CancellationToken) TakeFromAny(BlockingCollection<T>[], T, CancellationToken)

當觀察指定的取消語彙基元時,接受任何一個指定之 BlockingCollection<T> 執行個體中的項目。Takes an item from any one of the specified BlockingCollection<T> instances while observing the specified cancellation token.

ToArray() ToArray() ToArray() ToArray()

BlockingCollection<T> 執行個體,將其中項目複製到新陣列。Copies the items from the BlockingCollection<T> instance into a new array.

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

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TryAdd(T) TryAdd(T) TryAdd(T) TryAdd(T)

嘗試將指定的項目加入至 BlockingCollection<T>Tries to add the specified item to the BlockingCollection<T>.

TryAdd(T, Int32) TryAdd(T, Int32) TryAdd(T, Int32) TryAdd(T, Int32)

嘗試在指定的時間週期內,將指定的項目加入 BlockingCollection<T>Tries to add the specified item to the BlockingCollection<T> within the specified time period.

TryAdd(T, Int32, CancellationToken) TryAdd(T, Int32, CancellationToken) TryAdd(T, Int32, CancellationToken) TryAdd(T, Int32, CancellationToken)

當觀察取消語彙基元時,嘗試在指定的時間週期內,將指定的項目加入 BlockingCollection<T>Tries to add the specified item to the BlockingCollection<T> within the specified time period, while observing a cancellation token.

TryAdd(T, TimeSpan) TryAdd(T, TimeSpan) TryAdd(T, TimeSpan) TryAdd(T, TimeSpan)

嘗試將指定的項目加入至 BlockingCollection<T>Tries to add the specified item to the BlockingCollection<T>.

TryAddToAny(BlockingCollection<T>[], T) TryAddToAny(BlockingCollection<T>[], T) TryAddToAny(BlockingCollection<T>[], T) TryAddToAny(BlockingCollection<T>[], T)

嘗試將指定的項目加入至任何一個指定的 BlockingCollection<T> 執行個體。Tries to add the specified item to any one of the specified BlockingCollection<T> instances.

TryAddToAny(BlockingCollection<T>[], T, Int32) TryAddToAny(BlockingCollection<T>[], T, Int32) TryAddToAny(BlockingCollection<T>[], T, Int32) TryAddToAny(BlockingCollection<T>[], T, Int32)

嘗試將指定的項目加入至任何一個指定的 BlockingCollection<T> 執行個體。Tries to add the specified item to any one of the specified BlockingCollection<T> instances.

TryAddToAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryAddToAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryAddToAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryAddToAny(BlockingCollection<T>[], T, Int32, CancellationToken)

嘗試將指定的項目加入至任何一個指定的 BlockingCollection<T> 執行個體。Tries to add the specified item to any one of the specified BlockingCollection<T> instances.

TryAddToAny(BlockingCollection<T>[], T, TimeSpan) TryAddToAny(BlockingCollection<T>[], T, TimeSpan) TryAddToAny(BlockingCollection<T>[], T, TimeSpan) TryAddToAny(BlockingCollection<T>[], T, TimeSpan)

當觀察指定的取消語彙基元時,嘗試將指定的項目加入任何一個指定的 BlockingCollection<T> 執行個體。Tries to add the specified item to any one of the specified BlockingCollection<T> instances while observing the specified cancellation token.

TryTake(T) TryTake(T) TryTake(T) TryTake(T)

嘗試從 BlockingCollection<T> 移除項目。Tries to remove an item from the BlockingCollection<T>.

TryTake(T, Int32) TryTake(T, Int32) TryTake(T, Int32) TryTake(T, Int32)

嘗試在指定的時間週期內,從 BlockingCollection<T> 中移除項目。Tries to remove an item from the BlockingCollection<T> in the specified time period.

TryTake(T, Int32, CancellationToken) TryTake(T, Int32, CancellationToken) TryTake(T, Int32, CancellationToken) TryTake(T, Int32, CancellationToken)

當觀察取消語彙基元時,嘗試在指定的時間週期內,從 BlockingCollection<T> 中移除項目。Tries to remove an item from the BlockingCollection<T> in the specified time period while observing a cancellation token.

TryTake(T, TimeSpan) TryTake(T, TimeSpan) TryTake(T, TimeSpan) TryTake(T, TimeSpan)

嘗試在指定的時間週期內,從 BlockingCollection<T> 中移除項目。Tries to remove an item from the BlockingCollection<T> in the specified time period.

TryTakeFromAny(BlockingCollection<T>[], T) TryTakeFromAny(BlockingCollection<T>[], T) TryTakeFromAny(BlockingCollection<T>[], T) TryTakeFromAny(BlockingCollection<T>[], T)

嘗試從任何一個指定的 BlockingCollection<T> 執行個體移除項目。Tries to remove an item from any one of the specified BlockingCollection<T> instances.

TryTakeFromAny(BlockingCollection<T>[], T, Int32) TryTakeFromAny(BlockingCollection<T>[], T, Int32) TryTakeFromAny(BlockingCollection<T>[], T, Int32) TryTakeFromAny(BlockingCollection<T>[], T, Int32)

嘗試從任何一個指定的 BlockingCollection<T> 執行個體移除項目。Tries to remove an item from any one of the specified BlockingCollection<T> instances.

TryTakeFromAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryTakeFromAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryTakeFromAny(BlockingCollection<T>[], T, Int32, CancellationToken) TryTakeFromAny(BlockingCollection<T>[], T, Int32, CancellationToken)

嘗試從任何一個指定的 BlockingCollection<T> 執行個體移除項目。Tries to remove an item from any one of the specified BlockingCollection<T> instances.

TryTakeFromAny(BlockingCollection<T>[], T, TimeSpan) TryTakeFromAny(BlockingCollection<T>[], T, TimeSpan) TryTakeFromAny(BlockingCollection<T>[], T, TimeSpan) TryTakeFromAny(BlockingCollection<T>[], T, TimeSpan)

嘗試從任何一個指定的 BlockingCollection<T> 執行個體移除項目。Tries to remove an item from any one of the specified BlockingCollection<T> instances.

明確介面實作

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

從目標陣列中的指定索引處開始,將 BlockingCollection<T> 執行個體中的所有項目複製到相容的一維陣列。Copies all of the items in the BlockingCollection<T> instance to a compatible one-dimensional array, starting at the specified index of the target array.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

取得值,這個值表示對 ICollection 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

取得可用以同步存取 ICollection 的物件。Gets an object that can be used to synchronize access to the ICollection. 不支援這個屬性。This property is not supported.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

提供集合中項目的 IEnumeratorProvides an IEnumerator for items in the collection.

IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator()

提供集合中項目的 IEnumerator<T>Provides an IEnumerator<T> for items in the collection.

Extension Methods

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

傳回DataTable,其中包含副本DataRow物件,指定輸入IEnumerable<T>物件其中泛型參數TDataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

將轉換IEnumerableIQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>)

傳回包含來源集合中每個節點祖系的項目集合。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName)

傳回包含來源集合中每個節點祖系的已篩選項目集合。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目之子代節點的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>)

傳回包含來源集合中每個項目和文件之子代項目的項目集合。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName)

傳回已篩選的項目集合,其中包含來源集合中每個項目和文件的子代項目。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>)

傳回來源集合中每個項目和文件的子項目集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName)

傳回來源集合中每個項目和文件的已篩選子項目集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>)

傳回包含來源集合中所有節點的節點集合,依據文件順序來排序。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目的子節點集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>)

在來源集合中,從每一個節點的父節點移除這些節點。Removes every node in the source collection from its parent node.

適用於

執行緒安全性

Dispose 方法不是安全執行緒。The Dispose method is not thread-safe. 所有公用和受保護的其他成員BlockingCollection<T>是安全執行緒,且可能會從多個執行緒同時使用。All other public and protected members of BlockingCollection<T> are thread-safe and may be used concurrently from multiple threads.

另請參閱