Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

BlockingCollection(Of T).GetConsumingEnumerable Method

.NET Framework 4.6 and 4.5

Provides a consuming IEnumerator(Of T) for items in the collection.

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

'Declaration
Public Function GetConsumingEnumerable As IEnumerable(Of T)

Return Value

Type: System.Collections.Generic.IEnumerable(Of T)
An IEnumerable(Of T) that removes and returns items from the collection.

ExceptionCondition
ObjectDisposedException

The BlockingCollection(Of T) has been disposed.

The following example shows how to use the GetConsumingEnumerable method:

'Imports System.Threading.Tasks 
'Imports System.Collections.Concurrent 

' Demonstrates: 
' BlockingCollection<T>.Add() 
' BlockingCollection<T>.CompleteAdding() 
' BlockingCollection<T>.GetConsumingEnumerable() 

Class ConsumingEnumerableDemo
    Shared Sub BC_GetConsumingEnumerable()
        Using bc As New BlockingCollection(Of Integer)()

            ' Kick off a producer task
            Task.Factory.StartNew(
                Sub()
                    For i As Integer = 0 To 9
                        bc.Add(i)
                        ' sleep 100 ms between adds
                        Thread.Sleep(100)
                    Next 

                    ' Need to do this to keep foreach below from hanging
                    bc.CompleteAdding()
                End Sub)
            ' 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. 
            For Each item In bc.GetConsumingEnumerable()
                Console.WriteLine(item)
            Next 
        End Using 
    End Sub 
End Class

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1
Show:
© 2015 Microsoft