About Threading and Types of Threading using a simple example in C#

 

Hey friends..! Welcome to my another blog post. In this post we have covered about threading and types of threading using a simple example in c#.net. An article question is very important to understand because in interviews it is mostly asked to fresher's or a developers with 1 year of experience. It is not only useful in interviews but also useful in implementing in an application. So its my personal request for fresher's to go through this article fully and understand it. If you have any doubts or queries just drop your valuable query in the below comment section. An Onlinebuff/Gurunatha Dogi's main motto to help readers in their technical field.

What is threading in C#?

One Line Definition : Threading means parallel code execution.

Threading helps us to executing one or more works in a parallel way or asynchronous way.

Asynchronous : Asynchronous means doing one of more tasks simultaneously. Here second work doesn't need to wait for first work to get complete they can work simultaneusly.

Synchronous : Synchronous means executing one or more work one after the other. Here second work have to wait till the first work gets completed.

The most common example of threading is available in our personal computer i.e. working on multiple applications simultaneously i.e To do multiple things on our personal computer like working on Microsoft Powerpoint + Adobe Photoshop + Windows Media Player to create business presentation and executing multiple task asynchronously. So for each application a new thread is been defined by processor as a execution path of a program. So the process to execute more than one task at a time is called as Threading.

Threads are lightweight processes and C# supports parallel execution of code through multithreading environment. Each and every thread have an independent execution path to run applications simultaneosly. That's why on your personal desktop when you open up multiple applications you are actually creating a multithread environment to run applications simultaneously.

C# supports threading : C# Console application, C# WPF, C# Windows Forms are always starts in a single thread environment created by Common Language Runtime (CLR). So when you creates a new thread in a console application it means you are actually creating a multithread environment. In the further article we will see how to create threading using an example.

Create Threading Step by Step

In c-sharp to implementing threading in our application first we need to import threading namespace i.e. "using System.Threading;" so by using thread objects we can use thread objects to create threads in applications.

After importing the namespace next step to create Thread objects as shown in below snippet.

using System;
using System.Threading;

class Program{

 public static void Main(){

  //Creates thread objects

  Thread objthread = new Thread();

 }

}

So after creating thread object let's invoke thread objects. To invoke thread objects let's demonstrate a small example. In this example first we will create multiple functions to check the output. We want to test wheather normally how both functions are executed. So let's test that.!


    class Program
    {
        static void Main(string[] args)
        {
            Method1();
            Method2();
        }

        static void Method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method One Executed " + i.ToString());
               
            }
        }

        static void Method2()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method Two Executed " + i.ToString());
                
            }
        }
    }

Display Output

Hey friends, as you saw in our above output that "Method1()" executed first then followed by "Method2()" executed in a synchronous way or sequential way. But what we want is that both of these function should execute simultaneously. Here were threading mechanism comes in handy. So for the same application let's add threading mechanism.

Step 1 : Import Threading Namespace

using System;
using System.Threading;

Step 2 : Create Thread Class and Thread Objects

using System;
using System.Threading;

class Program{

 public static void Main(){

  //Creates thread objects

  Thread objthread1 = new Thread(Method1);
  Thread objthread2 = new Thread(Method2);

 }

}

Step 3 : Invoke Thread Objects

using System;
using System.Threading;

class Program{

 public static void Main(){

  //Creates thread objects

  Thread objthread1 = new Thread(Method1);
  Thread objthread2 = new Thread(Method2);

  thread1.Start();
  thread2.Start();

 }

        static void Method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method One Executed " + i.ToString());

                Thread.Sleep(4000); //Sleep for 4 seconds

               
            }
        }

        static void Method2()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method Two Executed " + i.ToString());
                Thread.Sleep(4000); //Sleep for 4 seconds
                
            }
        }

}
Display Output

In our above code example of a Console Application we have created two functions (Method1 and Method2 respectively). Inside both method bodys we have created the loop of 10 times and after each we have waited for 4 seconds. Kindly note for waiting we have used "Thread" class function i.e. "Sleep()". Now inside the main function body we have created the thread objects from "Thread" class and using those objects we called "Start()" function and using that "Start()" function we started execution of both function simultaneously.

C# supports threading and on dotnet platform CLR automatically starts a console application with a single thread or Main thread. If we add a new thread in our main program then main program creates a new thread (worker thread) and both of these threads starts their work in a multithread environment simultaneously. An example of multithread is shown below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Threading
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread objworkerthread = new Thread(WorkerThread);
            objworkerthread.Start();            

            for (int k = 0; k <= 10; k++)
            {
                Console.WriteLine("main thread");
                Thread.Sleep(4000); //Sleep for 4 seconds
            }


        }

        static void WorkerThread()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("worker thread");
                Thread.Sleep(4000); //Sleep for 4 seconds
               
            }
        }

        
    }
}

So friends, as per both examples it is been proved that using threading we can execute mutiple task in a parallel way.

Threads share data if they have a common reference to the same object instance. Let me prove it by using an example.


class Program
    {
        private bool ShareData;
        static void Main(string[] args)
        {

            Program prg = new Program();

            Thread objThread = new Thread(prg.Company1);
            objThread.Start();
            prg.Company2();

        }

        public void Company1()
        {
            if (!ShareData)
            {
                ShareData = true;
                Console.WriteLine("Data already shared");

            }

        }

        public void Company2()
        {
            if (!ShareData)
            {
                ShareData = true;
                Console.WriteLine("Data already shared");

            }

        }

        
    }

If you see above example we have two methods "Company1" and "Company2" and both of these methods prints some output if "shareData" variable is false. The first method "Company1" is executed by using thread object and second method is executed by calling. Ideally display output should been printed twice but we got only single output.

This happen because C# opens main method in a single thread and main method opens up new thread to start "Company1". This result "Data already shared" is been printed only once.

Understand Thread.Join(), Thread.Sleep() and Thread.Abort() Methods

Join(), Sleep() and Abort() these are three main methods of a thread class which is widely used in a multithread implementation.

Thread.Join() Method with example

Join waits for a thread to end. Join method when attached to any thread it makes that thread to finish its execution first or to end first and halts other processes. In simple words we can wait for another thread to end by calling its Join method. We can include TimeSpan or milliseconds with Join method.

Example

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

            Thread objThread = new Thread(ProcessJoin);
            objThread.Start();
            objThread.Join();
            Console.WriteLine("work completed..!");

        }

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

            }

        }

            
    }

Above code is a simple example of Join method. In this program we have created a new thread for method "ProcessJoin" and waited "ProcessJoin" to finish its work by adding Join method. Above example first prints "work is in progress..!" 10 times and exit then prints "work completed..!" and main method exit.

Display Output

Thread.Sleep() Method with example

Sleep method is used to suspend the current thread or pauses the current thread for specific time. The time can be specified in milliseconds or TimeSpan and in Sleep mode thread does not consume and CPU resources which indirectly saves the memory for other processes.

Example

using System.Threading;
using System.Diagnostics;

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

            Thread objThread = new Thread(ProcessJoin);
            objThread.Start();
            objThread.Join();
            
           
           
            stopWatch.Stop();           
            TimeSpan ts = stopWatch.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 ProcessJoin()
        {
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("work is in progress..!");
                Thread.Sleep(4000); //Sleep for 4 seconds

            }

        }


    }

In the above code example "ProcessJoin" makes a loop for 5 times and for every loop it sleeps for 4 seconds. We have calculated total sleep time using using System.Diagnostics namespace "stopwatch".

Display Output

Thread.Abort() Method with example

Thread.Abort method helps to terminate or to end thread. Abort method raises ThreadAbortException in the thread to do process of termination and throws ThreadAbortException in the thread to abort it. This exception can be caught in the application code. The complete termination can be done by calling Join method after Abort method.

            Thread objThread = new Thread(ProcessJoin);
            objThread.Start();
            objThread.Join();

            objThread.Abort();

Types of Threads in C#

There two types of threads in c#.

1. Foreground Thread

2. Background Thread

Foreground Thread

Foreground threads are those threads which keeps on running to complete its work even if the main thread quits. In simple words worker thread will keeps on running (to complete work) even if the main thread has ended the session. Here lifespan of workerthread is not dependent on the main thread. Worker thread can be alive without main thread.

Example

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

            Thread objThread = new Thread(WorkerThread);
            objThread.Start();
            Console.WriteLine("Main Thread Quits..!");


        }

        static void WorkerThread()
        {
            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..!");

        }


    }

In the above example of foreground thread, "workerthread" is still in process even if the main thread has ended session.

Display Output

Background Thread

Background threads are those threads which quits if the main application method quits. Here lifespan of worker thread is dependent on the main thread. Worker thread quits if the main application thread quits. To use the background thread in an application we need to set a property called "IsBackground" to true.

Example

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

            Thread objThread = new Thread(WorkerThread);
            objThread.Start();

            objThread.IsBackground = true;

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


        }

        static void WorkerThread()
        {
            

            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..!");

        }


    }


In the above example of background thread. We have set property "IsBackground" to true to make a background thread. Here in background thread worker thread quits after the main application thread quits.

Display Output

So hey friends..! Thank you for reading this article still more to cover in threading like threading locks, AutoResetEvent and ManualResetEvent, debug threads which we will try to cover in our upcoming articles. If you have any doubts or suggestion to improve this article kindly drop your valuable comment in the below comment section. Kindly care to share this article with your friends on FB, Twitter and Google +. Thank You..!

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Aug
24
2014

Understand difference between Early Binding and Late Binding with an example in C#

CLICK TO READ FULL ARTICLE

Views - 21686 |Category - C#

Aug
10
2014

Complete Tutorial on C# 3.0 VAR Keyword with example

CLICK TO READ FULL ARTICLE

Views - 6295 |Category - C#

Aug
07
2014

Complete Tutorial on Dynamic Keyword in C# 4.0 with an example

CLICK TO READ FULL ARTICLE

Views - 7327 |Category - C#

Aug
04
2014

Understand Reflection in C#.NET with example

CLICK TO READ FULL ARTICLE

Views - 17766 |Category - C#

Jul
23
2014

Understand Constants in C# with an example

CLICK TO READ FULL ARTICLE

Views - 5709 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

dnkob

 

 
Comments

Posted by DIgvijay Ghatage on 2015-02-05

Nice Article..... Please explain what is singlonton pattern and singlonton class in detail?