Friday, February 21, 2020

Multi Threading in C# (using Thread class)


MultiThreading in C# : Now a days multiple ways we have to create thread in C#, Thread class is present in
C# from inception.Thread class takes a ThreadStart/ParameterisedThreadStart delegate, or simply we can pass a parameterised or non parameterised method which returns void.
In case of parameterised method we can pass a single parameter of type Object.
Please see the below example for more clarity:

public class Program
    {
        static void Main(string[] args)
        {
            // calling non-parameterised method in Thread class 
            Thread child = new Thread(ThreadOperation);
            child.Start();

            // calling parameterised method in Thread class 
            Thread paramterisedChild = new Thread(ThreadParamterisedObject);
            paramterisedChild.Start("Niranjan"); //--- Any object we can pass to thread---//

            // additional work done by main thread
            for(int i=0;i<10 font="" i="">
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Main Thread " + i);
            }
            Console.WriteLine(" Good bye from Main");
            Console.ReadLine();
        }
        //---This method will be called by child thread---.
        public static void ThreadOperation()
        {
            for (int i = 0; i < 10; i++){
                
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Child Thread " + i);
            }
        }
        //---This method need one paramter of type object---.
        public static void ThreadParamterisedObject(object obj)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500); //pausing thread for 500 milisecond.
                Console.WriteLine(" Child Thread " + obj.ToString());
            }
        }
    }



No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...