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:

  • 生成者/使用者模式的实现;@no__t 为 IProducerConsumerCollection<T> 接口的包装。An implementation of the producer/consumer pattern; BlockingCollection<T> is a wrapper for the IProducerConsumerCollection<T> interface.

  • 并发添加和删除多个线程中的项,@no__t 为-0,Take 方法。Concurrent addition and removal of items from multiple threads with the Add and Take methods.

  • 一个绑定集合,用于在集合已满或为空时阻止 @no__t 0 和 @no__t 1 操作。A bounded collection that blocks Add and Take operations when the collection is full or empty.

  • 使用 @no__t 或 @no__t 方法中的 CancellationToken 对象取消 @no__t 0 或 @no__t 操作。Cancellation of Add or Take operations by using a CancellationToken object in the TryAdd or TryTake method.

重要

此类型实现 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> 的公共和受保护成员都是线程安全的,并且可以从多个线程同时使用。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. @no__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>,以对 @no__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> 类似于传统阻塞队列数据结构,只不过基础数据存储机制将作为 @no__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. 生成线程可以调用 @no__t 0 方法,以指示不再添加项。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.

Add 和 @no__t 操作通常在循环中执行。Add and Take operations are typically performed in a loop. 您可以通过将 @no__t 0 对象传入 @no__t 或 TryTake 方法取消循环,然后在每次迭代时检查令牌的 @no__t 属性的值。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.

创建 @no__t 0 对象时,不仅可以指定限制容量,还可以指定要使用的集合类型。When you create a BlockingCollection<T> object, you can specify not only the bounded capacity but also the type of collection to use. 例如,你可以为先进先出(FIFO)行为指定 @no__t 0 对象,或为后进先出(LIFO)行为指定 @no__t 1 对象。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. 如果直接更改基础集合,@no__t 0 对象可能会损坏。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>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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> 的公共和受保护成员都是线程安全的,并且可以从多个线程同时使用。All other public and protected members of BlockingCollection<T> are thread-safe and may be used concurrently from multiple threads.

另请参阅