using System.Collections.Concurrent; BlockingCollectionbc = new BlockingCollection (); // Add items to the collection for (int i = 0; i < 10; i++) { bc.Add(i); } // Get the enumerable and consume items foreach (int item in bc.GetConsumingEnumerable()) { Console.WriteLine(item); }
using System.IO; using System.Text; using System.Threading.Tasks; using System.Collections.Concurrent; BlockingCollectionIn this example, we create a new BlockingCollection of strings and a Task to write lines from a file to the collection. We then use the GetConsumingEnumerable method to consume each line in the collection and write it to a new file. When the consumer is done, we wait for the producer Task to complete. The System.Collections.Concurrent namespace provides a collection of thread-safe data structures that can be used in multi-threaded applications.bc = new BlockingCollection (); // Create a new Task to write to the collection Task producer = Task.Run(() => { // Open a file and read lines using (StreamReader sr = new StreamReader("testfile.txt")) { string line; while ((line = sr.ReadLine()) != null) { // Add lines to the collection bc.Add(line); } } // Complete the collection bc.CompleteAdding(); }); // Get the enumerable and consume items foreach (string item in bc.GetConsumingEnumerable()) { // Write each item to a new file using (StreamWriter sw = new StreamWriter("outfile.txt", true, Encoding.UTF8)) { sw.WriteLine(item); } } // Wait for the producer Task to complete producer.Wait();