liveBook · Manning

CompleteAdding

As explained in C# Concurrency: Asynchronous and multithreaded programming

A BlockingCollection<T> method that marks the collection as unable to accept additional items after existing items have been consumed.

CompleteAdding marks a BlockingCollection<T> work queue as closed to new items. Consumers continue processing queued items, then exit when the queue is empty. section 8.2.2 section 13.2.2

Use the operation as the producer-consumer handoff:

  • Add work items while production continues. section 8.2.2
  • Call CompleteAdding after the producer has submitted the final item. section 8.2.2
  • Consume with GetConsumingEnumerable; foreach blocks when empty and exits after all remaining items are processed. section 8.2.2 section 13.2.2
  • Do not call Add or TryAdd after completion; either operation throws InvalidOperationException. section 13.2.2

Closing a background mail queue

A MailMerger enqueues prepared messages, while a dedicated background thread iterates over GetConsumingEnumerable and sends them. Stop calls _queue.CompleteAdding(), allowing the worker to finish queued mail before exiting.

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains the producer-consumer lifecycle, blocking enumeration, draining behavior, and post-completion exceptions.
Examples
Uses a background mail queue and a ten-thread integer-processing example to demonstrate draining and coordinated shutdown.
What it assumes
Assumes familiarity with BlockingCollection<T>, Add, foreach, consumer threads, and producer-consumer queues.
What you can do after
Operate a BlockingCollection<T> work queue with an explicit producer shutdown and safely draining consumers.
How it connects
Connects BlockingCollection<T> with producer-consumer queues, GetConsumingEnumerable, Add, TryAdd, and dedicated threads.

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.