Wednesday, 2 September 2015

Thread-Safe Collection using blockingcollection and Task in C#

// Thread-Safe Collection using blockingcollection and Task

static void Main(string[] args)
        {
         
            BlockingCollection<int> block = new BlockingCollection<int>();
         
            var task1 = Task.Factory.StartNew(() => {
                foreach (int i in block.GetConsumingEnumerable()) // GetConsumingEnumerable is used to take element from collection and deleted it
                {
                    Console.WriteLine("Task 1 data {0}", i);
                }

             
               
            });
            var task2 = Task.Factory.StartNew(() =>
            {
                foreach (int i in block.GetConsumingEnumerable())
                {
                    Console.WriteLine("Task 2 data {0}", i);
                }

               
            });

            var task3 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    block.Add(i);
                }
                block.CompleteAdding(); //Its used to check , BlockingCollection list is added or not
               
            });
         
            task3.Wait(); // why we add task3.Wait() , becoz first of all we are going to add item into BlockingCollection  list then we are going to loop on this list at a same time
            Task.WaitAll(task1, task2); // after finished task3 , these task1 and task2 is going to wait until they finished work
            Console.ReadLine();
        }

OutPut->Task 1 data 0
Task 2 data 1
Task 1 data 2
Task 2 data 3

No comments:

Post a Comment