BlockingCollection Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection. : BlockingCollection « Collections Data Structure « C# / C Sharp






BlockingCollection Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection.

 
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

class AddTakeDemo
{
    static void Main()
    {
        BlockingCollection<int> bc = new BlockingCollection<int>();
        Task t1 = Task.Factory.StartNew(() =>
        {
            bc.Add(1);
            bc.Add(2);
            bc.Add(3);
            bc.CompleteAdding();
        });
        Task t2 = Task.Factory.StartNew(() =>
        {
            try
            {
                while (true) Console.WriteLine(bc.Take());
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("Exception");
            }
        });
        Task.WaitAll(t1, t2);
    }
}

   
  








Related examples in the same category