Wednesday, September 26, 2012

Threading example in C#

using System;
using System.Text;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

namespace Threading_Demo
{
    public class Threading
    {
        ArrayList data = null;

        ManualResetEvent[] totalEvents = null;
        
        public Threading(ArrayList data)
        {
            this.data = data;
            this.totalEvents = new ManualResetEvent[data.Capacity];
        }

        public void ProcessThreads()
        {
            WaitCallback callBack = new WaitCallback(ProcessData);

            int resetIndex = 0;

            foreach (object item in data)
            {
                //Create thread and add it in pool
                ThreadPool.QueueUserWorkItem(callBack, resetIndex + "#" + item);

                //Create new event
                totalEvents[resetIndex++] = new ManualResetEvent(false);
            }

            if (totalEvents != null)
            {
                WaitHandle.WaitAll(totalEvents);
            }
        }

        private void ProcessData(object state)
        {
            string objState = state as string;
            string[] stateParam = objState.Split('#');

            if (stateParam.Length == 2)
            {
                int threadId = Convert.ToInt32(stateParam[0]);

                if (!string.IsNullOrEmpty(stateParam[1]))
                {
                    string data = stateParam[1];

                    //Process data
                    Console.Write("Thread Id: " + threadId.ToString() + " Data: " + data.ToString() + "\n");

                    //Signal to pool after current thread finished it's porceesing
                    totalEvents[threadId].Set();
                }
            }
        }        
    }

    class Program
    {
        static void Main(string[] args)
        {
            ArrayList data = new ArrayList(5) { "One", "Two", "Three", "Four", "Five"};

            Threading thread = new Threading(data);
            thread.ProcessThreads();

        }
    }
}