BlockingCollectioncollection = new BlockingCollection (10); Parallel.For(0, 20, i => { collection.Add(i); // may block if collection is full }); collection.CompleteAdding(); foreach (int item in collection.GetConsumingEnumerable()) { Console.WriteLine(item); // prints integers from 0 to 19 }
BlockingCollectionThis example creates a BlockingCollection of strings with no maximum capacity. It then uses two tasks: one to produce 10 items and add them to the collection, and another to consume all the items in the collection. The producer task prints a message for each item it produces, while the consumer task prints a message for each item it consumes. The WaitAll() method is used to wait for both tasks to complete. Package library: System.Collections.Concurrent.collection = new BlockingCollection (); Task producer = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { string item = "Item " + i.ToString(); collection.Add(item); Console.WriteLine("Produced item: " + item); } collection.CompleteAdding(); }); Task consumer = Task.Factory.StartNew(() => { foreach (string item in collection.GetConsumingEnumerable()) { Console.WriteLine("Consumed item: " + item); } }); Task.WaitAll(producer, consumer);