C# Threading


Thread is a light weight process. A process has at least one thread which is commonly called as main thread which actually executes the application code. A single process can have multiple threads.
To define Threading in a one line, means parallel work or code execution. To perform any multiple task simultaneously means Threading.
For example executing Microsoft PPTX and Excel simultaneously in a desktop, laptop or any device is known as Threading.
Work or a code task is always been executed in a two ways i.e. Synchronous or Asynchronous way.
Synchronous way means where work multiple jobs are executed one after the other. Here Work 2 have to wait till Work 1 is completed same way the others as shown in below image.

Asynchronous means multiple work has been executed simultaneously like doing multitask at a same time.

Execution of Microsoft Powerpoint and Excel asynchronously on our personal laptop is most common example for threading. System generates new thread for each application been launched because every thread has an independent execution path to run these applications asynchronously.
C# widely supports threading in Console Application, Windows Form, WPF so when we create a new thread in a console app it means we are making it multithread environment.
CSharp Threading step by step using example
Here we will demonstrate threading using an example step by step, We will do this example in a visual studio 2015.
In order to create threading in C# VS 2015 we need to import threading namespace i.e. System.Threading using this namespace we can create thread object which can help us to create thread applications.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleThreadingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread th = Thread.CurrentThread;
        }
    }
}




As you saw in an above image that without Threading Namespace we can't able to use Thread classes and objects. So it is must to import threading namespace in-order to create Threading application.
Hope till now you have understood everything.
Now to make you understand more better we will create two methods i.e. Work1 and Work2 respectively and inside that we will make a FOR loop. Here we want to test how both functions are executes.

 class Program
    {
        static void Main(string[] args)
        {
            Work1();
            Work2();
        }

        static void Work1()
        {
            for(int i = 1; i <=10; i++)
            {

                Console.WriteLine("Work 1 is called " + i.ToString());

            }

        }

        static void Work2()

        {
            for (int i = 1; i <= 10; i++)
            {

                Console.WriteLine("Work 2 is called " + i.ToString());

            }

        }
    }

As you see in above code snippet we have created both normal functions and that we will execute, So let's run it and see the output.

If you see both functions / methods ran synchronously i.e one after the other. Here Work 2 have to wait till Work 1 has finished his loop.
But in this fast moving world we have a habbit of doing multi-tasking so here also in a same way we need some kind of mechanism which helps us to run both methods asynchronously i.e simultaneously. So to make that c# has a mechanism called Threading.
So we understood the problem and now we will see how threading helps to fix this problem i.e. Running both methods simultaneously.
Step 1
First and foremost step to import Threading namespace.
using System;
using System.Threading;
Step 2
Here in this step we will create thread objects in our Main method.
 class Program
    {
        static void Main(string[] args)
        {
            Thread oThreadone = new Thread(Work1);
            Thread oThreadtwo = new Thread(Work2);

           
        }
  }
Step 3
In this step we will invoke our thread objects
 class Program
    {
        static void Main(string[] args)
        {
            Thread oThreadone = new Thread(Work1);
            Thread oThreadtwo = new Thread(Work2);
                
             oThreadone.Start();
            oThreadtwo.Start();

           
        }
  }
As you see we have invoked Thread objects successfully. Now let's run this program to see the Output.

As you see in output that Work2 method is also simultaneously executing with Work1 method it means both methods are working asynchronously.
So as per above examples it is been concluded that using threading we can execute mutiple work in a asynchronously.
For creating threading application there some important methods which used regularly for implementing threading.
  1. 1 : Thread Join
  2. 2 : Thread Sleep
  3. 3 : Thread Abort
Use of Thread Join
Thread.Join() make thread to finish its work or makes other thread to halt until it finishes work. Join method when attached to any thread, it makes that thread to execute first and halts other threads. Now on the same we will see a simple example where we apply Join method to thread.
class Program
    {
       
        static void Main(string[] args)
        {

            Thread oThread = new Thread(MethodJoin);
            oThread.Start();
            oThread.Join();
            Console.WriteLine("work completed..!");

        }

        static void MethodJoin()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("work is in progress..!");

            }

        }

           
    }

So hey friends as you see we have created a method called "MethodJoin()" and attached it with a Thread.Join method so as per our theory discussion above "MethodJoin()" will execute first and then main method let's see the output.

As you see the output "MethodJoin" is been executed first i.e. output as "work is in progress..!" and then Main method of console application executed i.e. output as "work completed..!"
Use of Thread Sleep
Thread.Sleep a method used to suspend current thread for a specific interval of time. Time can be specified in milliseconds or Timespan. While in a Sleep mode a method does not consumes any CPU resources so indirectly it save memory for other thread processes.
On the same we will create a simple example where in the for loop while printing output we will make a thread to sleep for 4000 milliseconds i.e. 4 secs for per print and total we are going to print 6 outputs. To count it properly we have used .NET Diagnostics namespace which allows us to use Stopwatch and TimeSpan to count elapsedTime. Complete example is shown below
using System.Threading;
using System.Diagnostics;

    class Program
    {
       
        static void Main(string[] args)
        {
            Stopwatch stWatch = new Stopwatch();
            stWatch.Start();

            Thread oThread = new Thread(ProcessSleep);
            oThread.Start();
            oThread.Join();

            stWatch.Stop();          
            TimeSpan ts = stWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}",ts.Hours, ts.Minutes, ts.Seconds);
            Console.WriteLine("TotalTime " + elapsedTime);
           
            Console.WriteLine("work completed..!");

        }

        static void ProcessSleep()
        {
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("work is in progress..!");
                Thread.Sleep(4000); //Sleep for 4 seconds

            }

        }


    }

As you see from above example we have implemented Sleep method in a ProcessSleep method and made thread to sleep for 4 secs for each print. For only to show you total time consumed to print all output we have used Diagnostics.Stopwatch and Diagnostics.Timespan. Output is shown below.

Use of Thread Abort
As name implies "Abort" so same way Thread.Abort helps to end or abort any thread to process it further. It raises ThreadAbortException in the thread for process of termination.
Thread objThread = new Thread(ProcessJoin);
objThread.Start();
objThread.Join();

objThread.Abort();
Types of Threads in C#
There are two types of Thread in Csharp i.e. Foreground Thread and Background Thread. Further let's see the uses of these threads.
Foreground Thread
As we know that Main method is also runs on single thread, So in a Main method when we attach any other method to a thread it means we are making a multithread application. Foreground threads are those threads which keeps running until it finishes his work even if the Main method thread quits its process. To make you understand more better let me show you. Lifespan of foreground threads does not depends on main thread.

         class Program
    {
       
        static void Main(string[] args)
        {
            Thread oThread = new Thread(WorkThread);
            oThread.Start();
            Console.WriteLine("Main Thread Quits..!");
        }

        static void WorkThread()
        {
            for (int i = 0; i <= 4; i++)
            {
                Console.WriteLine("Worker Thread is in progress..!");
                Thread.Sleep(2000); //Sleep for 2 seconds

            }
            Console.WriteLine("Worker Thread Quits..!");

        }


    }


As you see output even if the Main thread quits then also WorkThread() continue to execute and complete its work. This was an ideal example to understand foreground thread. If you guys know any better example feel free to post under comment section your ideas will help us to write this article in more better and help to share knowledge.
Background Thread
Background thread is just opposite of foreground thread here background thread quits its job when main thread quits. Here lifespan of background threads depends on main thread. In order to implement background thread in a program we need to set property called IsBackground to true.
Thread oThread = new Thread(WorkThread);
oThread.IsBackground = true;

class Program
   {
      
       static void Main(string[] args)
       {

           Thread oThread = new Thread(WorkThread);
           oThread.Start();

           oThread.IsBackground = true;

           Console.WriteLine("Main Thread Quits..!");


       }

       static void WorkThread()
       {
          

           for (int i = 0; i <= 4; i++)
           {
               Console.WriteLine("Worker Thread is in progress..!");
               Thread.Sleep(2000); //Sleep for 2 seconds

           }

           Console.WriteLine("Worker Thread Quits..!");

       }


   }




Share this

Related Posts

Previous
Next Post »