BlockingCollection<T> 類別

定義

提供安全執行緒集合適用的封鎖和界限容量,這個集合會實作 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>
屬性
實作

範例

下列範例顯示如何從封鎖集合同時新增和接受專案: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. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。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> 的所有其他 public 和 protected 成員都是安全線程,而且可以從多個執行緒同時使用。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 方法,然後在每個反復專案上檢查 token 的 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> 類別的新執行個體。Initializes a new instance of the BlockingCollection<T> class without an upper-bound.

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> 類別的新執行個體。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> 類別的新執行個體。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

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

Count

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

IsAddingCompleted

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

IsCompleted

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

方法

Add(T)

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

Add(T, CancellationToken)

將項目加入至 BlockingCollection<T>Adds the item to the BlockingCollection<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)

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

CompleteAdding()

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

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()

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

Dispose(Boolean)

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

Equals(Object)

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

(繼承來源 Object)
GetConsumingEnumerable()

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

GetConsumingEnumerable(CancellationToken)

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

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

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

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
Take()

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

Take(CancellationToken)

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

TakeFromAny(BlockingCollection<T>[], T)

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

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()

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

ToString()

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

(繼承來源 Object)
TryAdd(T)

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

TryAdd(T, Int32)

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

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)

嘗試將指定的項目加入至 BlockingCollection<T>Tries to add the specified item to the BlockingCollection<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)

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

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)

當觀察指定的取消語彙基元時,嘗試將指定的項目加入至任何一個指定的 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)

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

TryTake(T, Int32)

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

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)

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

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)

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

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)

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

明確介面實作

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 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot

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

IEnumerable.GetEnumerator()

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

IEnumerable<T>.GetEnumerator()

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

擴充方法

CopyToDataTable<T>(IEnumerable<T>)

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 IEnumerable<T> 物件複本的 DataRowReturns 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

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

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

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)

傳回包含來源集合中每個節點祖系的已篩選項目集合。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>)

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

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)

傳回已篩選的項目集合,其中包含來源集合中每個項目和文件的子代項目。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>)

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

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>)

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

Nodes<T>(IEnumerable<T>)

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

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> 的所有其他 public 和 protected 成員都是安全線程,而且可以從多個執行緒同時使用。All other public and protected members of BlockingCollection<T> are thread-safe and may be used concurrently from multiple threads.

另請參閱