liveBook · Manning

GetConsumingEnumerable

As explained in C# Concurrency: Asynchronous and multithreaded programming

A BlockingCollection<T> method that returns an enumerable which removes items as they are iterated and waits when the collection is empty until production ends or an item becomes available.

GetConsumingEnumerable returns an enumerable for a BlockingCollection<T> work queue. A foreach loop removes items as it processes them, waits when the queue is empty, and ends after CompleteAdding is called and queued items are exhausted. section 8.2.2

Use it to coordinate producers and consumers without manually implementing queue-waiting logic:

  • Start one or more consumer threads, each iterating over the same consuming enumerable. section 13.2.2
  • Add work from producer code; each item is processed once, although completion output can appear out of order with multiple consumers. section 13.2.2
  • Call CompleteAdding when production ends so waiting consumers can exit after processing remaining items. section 8.2.2
  • Combine the queue with bounded capacity when producers must block rather than grow the collection without limit. section 13.2.2

Background work queue

A background mail processor can run foreach (var current in _queue.GetConsumingEnumerable()), send each queued message, catch and log per-item failures, and stop naturally after _queue.CompleteAdding().

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains blocking, item consumption, completion, multiple consumers, ordering effects, and bounded-capacity interaction.
Examples
Uses a mail-processing queue and ten worker threads processing values from 0 through 99.
What it assumes
Assumes familiarity with foreach, threads, and BlockingCollection<T>; teaches queue consumption and shutdown behavior through implementation.
What you can do after
Operate/configure a BlockingCollection<T> work queue with blocking consumers, orderly shutdown, and optional backpressure.
How it connects
Ties consuming enumeration to BlockingCollection<T>, work queues, foreach, CompleteAdding, producer-consumer coordination, and bounded capacity.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.