Share Data Between Tasks - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Share Data Between Tasks

Demo Code


using System;/*from   w  w  w .  j av  a 2 s  .  c o m*/
using System.Collections.Concurrent;
using System.Threading.Tasks;

class MainClass
    {
        static void Main(string[] args)
        {
            ConcurrentStack<int> cStack = new ConcurrentStack<int>();

            Task task1 = Task.Factory.StartNew(() => addNumbersToCollection(cStack));
            Task task2 = Task.Factory.StartNew(() => addNumbersToCollection(cStack));
            Task task3 = Task.Factory.StartNew(() => addNumbersToCollection(cStack));

            Task.WaitAll(task1, task2, task3);

            Console.WriteLine("There are {0} items in the collection", cStack.Count);

            Console.WriteLine("\nMain method complete. Press Enter");
            Console.ReadLine();
        }

        static void addNumbersToCollection(ConcurrentStack<int> stack)
        {
            for (int i = 0; i < 1000; i++)
            {
                stack.Push(i);
            }
        }
    }

Result


Related Tutorials