BlockingCollection
provides us with an easier alternative for looping through a collection, and removing items without setting up a while
loop, and checking the IsCompleted
property. BlockingCollection
gives us the ability to do a simple foreach
loop with the GetConsumingEnumerable
method.
In this recipe, we are going to create a Console
application that initializes a range of source data and spins up a producer task to add the data to the collection. The consumer of the collection data will use the GetConsumingEnumerable
method to get IEnumerable<T>
for items in the collection.
Let's take a look at how to iterate over a BlockingCollection
with GetConsumingEnumerable
.
Start a new project using the C# Console Application project template and assign
Enumerate
as the Solution name.Add the following
using
directives to the top of yourProgram
class.using System; using System.Collections.Concurrent; using System.Linq...