Export (0) Print
Expand All

BlockingCollection<T>.GetConsumingEnumerable Method

Provides a consuming IEnumerator<T> for items in the collection.

Namespace:  System.Collections.Concurrent
Assembly:  System (in System.dll)

public IEnumerable<T> GetConsumingEnumerable()

Return Value

Type: System.Collections.Generic.IEnumerable<T>
An IEnumerable<T> that removes and returns items from the collection.

ExceptionCondition
ObjectDisposedException

The BlockingCollection<T> has been disposed.

The following example shows how to use the GetConsumingEnumerable method:

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);
            }
        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1

Windows Phone 8.1, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft