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;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class BlockingCollectionDemo
{
    static void Main()
    {
        AddTakeDemo.BC_AddTakeCompleteAdding();
        TryTakeDemo.BC_TryTake();
        FromToAnyDemo.BC_FromToAny();
        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 void BC_AddTakeCompleteAdding()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {

            // Spin up a Task to populate the BlockingCollection 
            using (Task t1 = Task.Factory.StartNew(() =>
            {
                bc.Add(1);
                bc.Add(2);
                bc.Add(3);
                bc.CompleteAdding();
            }))
            {

                // Spin up a Task to consume the BlockingCollection
                using (Task t2 = Task.Factory.StartNew(() =>
                {
                    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!");
                    }
                }))

                    Task.WaitAll(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 void BC_GetConsumingEnumerable()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {

            // Kick off a producer task
            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    bc.Add(i);
                    Thread.Sleep(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 hanging
                    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. 例如,可以指定ConcurrentQueue<T>先进先出 (FIFO) 行为的对象或ConcurrentStack<T>后进先出 (LIFO) 行为的对象。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()

获取当前实例的 Type Gets the Type of the current instance.

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

创建当前 Object 的浅表副本。 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.

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

为集合中的项提供 IEnumerator Provides 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.

适用于

线程安全性

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.

另请参阅