ConcurrentBag<T> ConcurrentBag<T> ConcurrentBag<T> ConcurrentBag<T> Class

定义

表示对象的线程安全的无序集合。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>ConcurrentBag<T>ConcurrentBag<T>ConcurrentBag<T>
属性
实现

示例

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

//<snippet1>
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");
    }

}
//</snippet1>
'<snippet1>
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
'</snippet1>

注解

包可用于存储对象时排序并不重要,并与不同的集,包支持重复项。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.

有关详细信息,请参阅文章常见问题:是否所有的新并发集合无锁定?并行编程与.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>() ConcurrentBag<T>() ConcurrentBag<T>()

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

ConcurrentBag<T>(IEnumerable<T>) ConcurrentBag<T>(IEnumerable<T>) ConcurrentBag<T>(IEnumerable<T>) ConcurrentBag<T>(IEnumerable<T>)

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

属性

Count Count Count Count

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

IsEmpty IsEmpty IsEmpty IsEmpty

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

方法

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

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

Clear() Clear() Clear() Clear()

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

CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32) 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) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

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

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

作为默认哈希函数。Serves as the default hash function.

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

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

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

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToArray() ToArray() ToArray() ToArray()

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

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

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
TryPeek(T) TryPeek(T) TryPeek(T) TryPeek(T)

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

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

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

显式界面实现

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) 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.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

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

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

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

IProducerConsumerCollection<T>.TryAdd(T) IProducerConsumerCollection<T>.TryAdd(T) IProducerConsumerCollection<T>.TryAdd(T) IProducerConsumerCollection<T>.TryAdd(T)

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

扩展方法

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<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) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) 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) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) 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) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

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

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

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

启用查询的并行化。Enables parallelization of a query.

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

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

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

返回元素集合,其中包含源集合中每个节点的上级。Returns a collection of elements that contains the ancestors of every node in the source collection.

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

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

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

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

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

返回元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

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

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

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

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

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

返回源集合中经过筛选的每个元素和文档的子元素集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

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

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

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

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

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

将源集合中的每个节点从其父节点中移除。Removes every node in the source collection from its parent node.

适用于

线程安全性

所有公共和受保护成员ConcurrentBag<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.

另请参阅