ConcurrentBag<T> Class

Definition

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)

Type Parameters

T

The type of the elements to be stored in the collection.

Inheritance
ConcurrentBag<T>
Attributes
Implements

Examples

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

Remarks

Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support duplicates. 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> accepts null as a valid value for reference types.

For more information, see the entry FAQ: Are all of the new concurrent collections lock-free? in the Parallel Programming with .NET blog.

Constructors

ConcurrentBag<T>()

Initializes a new instance of the ConcurrentBag<T> class.

ConcurrentBag<T>(IEnumerable<T>)

Initializes a new instance of the ConcurrentBag<T> class that contains elements copied from the specified collection.

Properties

Count

Gets the number of elements contained in the ConcurrentBag<T>.

IsEmpty

Gets a value that indicates whether the ConcurrentBag<T> is empty.

Methods

Add(T)

Adds an object to the ConcurrentBag<T>.

Clear()

Removes all values from the ConcurrentBag<T>.

CopyTo(T[], Int32)

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.

(Inherited from Object)
GetEnumerator()

Returns an enumerator that iterates through the ConcurrentBag<T>.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToArray()

Copies the ConcurrentBag<T> elements to a new array.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
TryPeek(T)

Attempts to return an object from the ConcurrentBag<T> without removing it.

TryTake(T)

Attempts to remove and return an object from the ConcurrentBag<T>.

Explicit Interface Implementations

ICollection.CopyTo(Array, Int32)

Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized

Gets a value indicating whether access to the ICollection is synchronized with the SyncRoot.

ICollection.SyncRoot

Gets an object that can be used to synchronize access to the ICollection. This property is not supported.

IEnumerable.GetEnumerator()

Returns an enumerator that iterates through the ConcurrentBag<T>.

IProducerConsumerCollection<T>.TryAdd(T)

Attempts to add an object to the ConcurrentBag<T>.

Extension Methods

CopyToDataTable<T>(IEnumerable<T>)

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

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

Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts 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. 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. 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. 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.

Applies to

Thread Safety

All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads. 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.

See also