Friday, March 8, 2013

Threading in C#.Net

Thread is an independent execution path, able to run simultaneously with the other threads.When you create  a c# client program the CLR automatically creates a single thread .i.e the "main" thread.
Example:

using System;
using System.Threading;

namespace threading
{
    class Program
    {
        static void Main()
        {
            Thread t = new Thread(display); //Creating a new thread.
            t.Start(); //starts the new thread
////// Simultaneously, do something on the main thread.
            for (int i = 0; i < 1000; i++)
            {
                //Thread.Sleep(1000);
                Console.Write("rayala"+"\t"); }
            Console.ReadKey();
        }
        public static void display()
        {
            for (int i = 0; i < 1000; i++)
            { //Thread.Sleep(2000);
                Console.Write("sagar"+"\t"); }
        }
    }
}
The above example prints the "rayala" and "sagar" simultaneously.i.e two threads running parallel.Do you want to see the execution of threads uncomment the lines Thread.Sleep(1000) and Thread.Sleep(2000) in the above code.

1 comment:

Unknown said...

Really Thanks, Very Simple And Focus