// create a new blocking collection BlockingCollectionnumbers = new BlockingCollection (); // add items to the collection Task.Run(() => { for (int i = 0; i < 10; i++) { numbers.AddToAny(i); } }); // iterate over the items in the collection foreach (int number in numbers) { Console.WriteLine(number); }
// create a new blocking collection with a maximum capacity of 5 items BlockingCollectionIn this example, we create a new blocking collection of strings with a maximum capacity of 5 items. We add 5 items to the collection, then use the AddToAny method to add a sixth item. Since the collection is full, this will block until a free slot becomes available. We then print the items in the collection to the console. The BlockingCollection class is part of the System.Collections.Concurrent namespace in the .NET Framework.names = new BlockingCollection (5); // add items to the collection names.AddToAny("Alice"); names.AddToAny("Bob"); names.AddToAny("Charlie"); names.AddToAny("Dave"); names.AddToAny("Eve"); // this will block until a free slot is available in the collection names.AddToAny("Frank"); // print the items in the collection foreach (string name in names) { Console.WriteLine(name); }