Friday, February 21, 2020

Multi Threading in C# : Returning a value from thread via shared variable.


Objective : We want to perform a long running operation in a separate thread and want result back from that thread.To achieve this we can use a shared/global variable,  thread will perform desired operation and then update global variable. please see below example for more clarity:

Note : variable and method used in below program is static, because we want to call them inside Main() which is static method.

 public class Program
  {
      static int resultFromThread = 0;
      #region Returing value from Thread

      public static void Main()
      {
          // if we want to call method with multiple paramter, we can use lambda expression to pass params to thread, like:

          Thread child = new Thread(() => Add(5, 4));
          child.Start();
          
          // some dummy operation performed by main
          for (int i = 0; i < 10; i++)
          {
              Thread.Sleep(100);
              Console.WriteLine("Some opeation performed by Main, side by side Child is doing it's own opeartion");
          }

          child.Join(); // Main will wait until child thread finished.
          Console.WriteLine("Child Thread has finished it's operation, now we can check resultFromThread");
          Console.WriteLine("value of resultFromThread "+ resultFromThread);
          Console.Read();

      }
      public static void Add(int a, int b)
      {
          Thread.Sleep(3000); //pausing thread for 3 sec.and then updating global variable resultFromThread.
          resultFromThread= a + b;
      }
      #endregion
  }

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());
            }
        }
    }



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 ...