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> 元素至現有一維 ArrayCopies 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 的淺層複本 (Shallow Copy)。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 的項目複製到 ArrayCopies 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>.

Extension Methods

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

傳回DataTable,其中包含副本DataRow物件,指定輸入IEnumerable<T>物件其中泛型參數TDataRowReturns 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)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies 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)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies 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)

將轉換IEnumerableIQueryableConverts 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.

適用於

執行緒安全性

所有 public 和 protected 成員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.

另請參閱