ConcurrentBag<T> 类

定义

表示对象的线程安全的无序集合。Represents a thread-safe, unordered collection of objects.

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

类型参数

T

要存储在集合中的元素的类型。The type of the elements to be stored in the collection.

继承
ConcurrentBag<T>
属性
实现

示例

下面的示例演示如何在 @no__t 中添加和移除项:The following example shows how to add and remove items from a ConcurrentBag<T>:

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

class ConcurrentBagDemo
{
    // Demonstrates:
    //      ConcurrentBag<T>.Add()
    //      ConcurrentBag<T>.IsEmpty
    //      ConcurrentBag<T>.TryTake()
    //      ConcurrentBag<T>.TryPeek()
    static void Main()
    {
        // Add to ConcurrentBag concurrently
        ConcurrentBag<int> cb = new ConcurrentBag<int>();
        List<Task> bagAddTasks = new List<Task>();
        for (int i = 0; i < 500; i++)
        {
            var numberToAdd = i;
            bagAddTasks.Add(Task.Run(() => cb.Add(numberToAdd)));
        }

        // Wait for all tasks to complete
        Task.WaitAll(bagAddTasks.ToArray());

        // Consume the items in the bag
        List<Task> bagConsumeTasks = new List<Task>();
        int itemsInBag = 0;
        while (!cb.IsEmpty)
        {
            bagConsumeTasks.Add(Task.Run(() =>
            {
                int item;
                if (cb.TryTake(out item))
                {
                    Console.WriteLine(item);
                    itemsInBag++;
                }
            }));
        }
        Task.WaitAll(bagConsumeTasks.ToArray());

        Console.WriteLine($"There were {itemsInBag} items in the bag");

        // Checks the bag for an item
        // The bag should be empty and this should not print anything
        int unexpectedItem;
        if (cb.TryPeek(out unexpectedItem))
            Console.WriteLine("Found an item in the bag when it should be empty");
    }

}
Imports System.Collections.Concurrent

Module ConcurrentBagDemo
    ' Demonstrates:
    ' ConcurrentBag<T>.Add()
    ' ConcurrentBag<T>.IsEmpty
    ' ConcurrentBag<T>.TryTake()
    ' ConcurrentBag<T>.TryPeek()
    Sub Main()
        ' Add to ConcurrentBag concurrently
        Dim cb As New ConcurrentBag(Of Integer)()
        Dim bagAddTasks As New List(Of Task)()
        For i = 1 To 500
            Dim numberToAdd As Integer = i
            bagAddTasks.Add(Task.Run(Sub() cb.Add(numberToAdd)))
        Next

        ' Wait for all tasks to complete
        Task.WaitAll(bagAddTasks.ToArray())

        ' Consume the items in the bag
        Dim bagConsumeTasks As New List(Of Task)()
        Dim itemsInBag As Integer = 0
        While Not cb.IsEmpty
            bagConsumeTasks.Add(Task.Run(Sub()
                                             Dim item As Integer
                                             If cb.TryTake(item) Then
                                                 Console.WriteLine(item)
                                                 itemsInBag = itemsInBag + 1
                                             End If
                                         End Sub))
        End While

        Task.WaitAll(bagConsumeTasks.ToArray())

        Console.WriteLine($"There were {itemsInBag} items in the bag")

        ' Checks the bag for an item
        ' The bag should be empty and this should not print anything
        Dim unexpectedItem As Integer
        If cb.TryPeek(unexpectedItem) Then
            Console.WriteLine("Found an item in the bag when it should be empty")
        End If
    End Sub
End Module

注解

当排序并不重要时,包可用于存储对象,而与集不同,包支持重复项。Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support duplicates. ConcurrentBag<T> 是一个线程安全包实现,适用于同一线程将生成和使用存储在包中的数据的情况。ConcurrentBag<T> is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag.

ConcurrentBag<T> 接受 null 作为引用类型的有效值。ConcurrentBag<T> accepts null as a valid value for reference types.

有关详细信息,请参阅项 FAQ:是否所有新的并发集合都无锁?在与 .NET 的并行编程中,For more information, see the entry FAQ: Are all of the new concurrent collections lock-free? in the Parallel Programming with .NET blog.

构造函数

ConcurrentBag<T>()

初始化 ConcurrentBag<T> 类的新实例。Initializes a new instance of the ConcurrentBag<T> class.

ConcurrentBag<T>(IEnumerable<T>)

初始化 ConcurrentBag<T> 类的新实例,该类包含从指定集合中复制的元素。Initializes a new instance of the ConcurrentBag<T> class that contains elements copied from the specified collection.

属性

Count

获取 ConcurrentBag<T> 中包含的元素数。Gets the number of elements contained in the ConcurrentBag<T>.

IsEmpty

获取一个值,该值指示 ConcurrentBag<T> 是否为空。Gets a value that indicates whether the ConcurrentBag<T> is empty.

方法

Add(T)

将对象添加到 ConcurrentBag<T> 中。Adds an object to the ConcurrentBag<T>.

Clear()

ConcurrentBag<T> 中删除所有值。Removes all values from the ConcurrentBag<T>.

CopyTo(T[], Int32)

从指定数组索引开始将 ConcurrentBag<T> 元素复制到现有一维 Array 中。Copies the ConcurrentBag<T> elements to an existing one-dimensional Array, starting at the specified array index.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnumerator()

返回循环访问 ConcurrentBag<T> 的枚举数。Returns an enumerator that iterates through the ConcurrentBag<T>.

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

ConcurrentBag<T> 元素复制到新数组。Copies the ConcurrentBag<T> elements to a new array.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
TryPeek(T)

尝试从 ConcurrentBag<T> 返回一个对象但不移除该对象。Attempts to return an object from the ConcurrentBag<T> without removing it.

TryTake(T)

尝试从 ConcurrentBag<T> 中移除和返回一个对象。Attempts to remove and return an object from the ConcurrentBag<T>.

显式界面实现

ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized

获取一个指示对 ICollection 的访问是否与 SyncRoot 同步的值。Gets a value indicating whether access to the ICollection is synchronized with the SyncRoot.

ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection. 不支持此属性。This property is not supported.

IEnumerable.GetEnumerator()

返回循环访问 ConcurrentBag<T> 的枚举数。Returns an enumerator that iterates through the ConcurrentBag<T>.

IProducerConsumerCollection<T>.TryAdd(T)

尝试将一个对象添加到 ConcurrentBag<T> 中。Attempts to add an object to the ConcurrentBag<T>.

扩展方法

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.

适用于

线程安全性

@No__t 的所有公共和受保护成员都是线程安全的,可从多个线程同时使用。All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads. 但是,通过 ConcurrentBag<T> 实现的接口之一(包括扩展方法)访问的成员不一定是线程安全的,并且可能需要由调用方进行同步。However, members accessed through one of the interfaces the ConcurrentBag<T> implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.

另请参阅