Saturday, 9 May 2015

Threading in C Sharp

What is Threading ?
Threading means parallel code execution. 
There are two types of thread.
1) Foreground thread 2) Background thread

Lets see a simple example without any threading.
class Program
    {
        static void Main(string[] args)
        {
            Function1();
            Function2();
            Console.ReadLine();
        }

        static void Function1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Runing from Func 1: {0}", i);
            }
        }

        static void Function2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Runing from Func 2: {0}", i);
            }
        }
    }

Output:



We can see, Its executing Function 1 first and then Function 2. Its a synchronous process. One by one functions are running.

Now Lets see with Threading.
First import System.Threading namespace
Using System.Threading ;
class Program
    {
        static void Main(string[] args)
        {
            //Created two threads
            Thread obj1 = new Thread(Function1);
            Thread obj2 = new Thread(Function2);

            //Invoke these threads
            obj1.Start();
            obj2.Start();

            Console.ReadLine();
        }

        static void Function1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Runing from Func 1: {0}", i);
                Thread.Sleep(500);
            }
        }

        static void Function2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Runing from Func 2: {0}", i);
                Thread.Sleep(500);
            }
        }
    }




As we can clearly see, both the threads running simultaneously.
Note* In reality Processor execute one thread for some time, and then execute another thread for some time, It happens so quickly that it appears that execution is happening simultaneously.

Two Kinds of Thread
1) Foreground Thread: Its a thread which keeps running till its execution is completed, Although main thread execution finished.
2) Background Thread: Its a thread which stops executing whenever main thread stops.




No comments:

Post a Comment