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
  }

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