Today, we will learn about threading in C#, why it is required and how to create a multi-threaded application in C#.

Threading is the way to run your code in parallel order. Means, you can execute multiple program’s code executions simultaneously without effective to each other. Somewhere I have read that “Threads are the lightweight process” but I do not agree with it. Actually, it is not process but part of the process and can say, run under the process to accomplish to any task.

Why Thread

This question is required to come here. Yes, we should know why it is required. As per the above definition. We can say, a thread is an execution path for the program. To run the program, we need at least a single thread and that is called Main thread or Primary Thread. It is responsible to execute the program.

The next question comes in mind that “Can we create multiple threads and if yes, why it is required to create multiple threads?”

The answer is yes, we can create multiple threads in an application or multiple threads could be inside in a process. Sometimes what happened, we try to accomplish the multiple tasks using a program parallel, but as we know, if we use the single thread and define each task in it, it will do it but in a synchronous manner. So, definitely, it will take time to complete it.

So, that is why we create multiple threads and assign the individual task to each to accomplish it. The conclusion is that we use thread to perform some task in the process and we are willing to perform multiple tasks at a time we can create multiple threads and divide the tasks between then to complete it in parallel mode. Each program runs under a process in Operating System and thread runs under the process. It means, a process can have multiple threads and that is called multi-threading. For example, suppose we have an operating system like Windows 10 and we have opened Microsoft Word application and writing something on it. When you open the task manager and go to processes section, you will find a process is running for Microsoft Word. Ok, Process is defined automatically by Operating System. But if we start writing in Microsoft Word then it creates thread internally for checking the grammar and spelling, formatting etc. So, these tasks can be done only by threading.

Basically, we need “System.Threading” namespace to include in the program to access “Thread” class for working with threads. This “Thread” class is responsible for creating the managing the thread and threads create using “Thread” class is called child thread. By default, every application has a main thread.

Practical Demonstration

Let’s do some practical demonstration and try to understand how to create a thread in C# and how it works. Let’s open the Visual Studio 2017 or any other version and create a Console Application. So, Go to File Menu and choose New and then Project. From the New Project windows, choose Visual C# and then chose “Console App (.Net Core)” template and provide the name as “ThreadDemo” and click to OK.

Now, we have a project ready along with a class as “Program” which contains the Main method. So, let import the System.Threading namespace and start coding. Here we will create two static methods as "Task1" and "Task2" and do simple looping and print 1 to 10 for both of tasks and let call these methods in Main method.

using System;
using System.Threading;
using static System.Console;

namespace ThreadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Run the task 1
            Task1();

            // Run the task 2
            Task2();
            ReadLine();
        }

        static void Task1()
        {
            for (int i = 1; i <= 10; i++)
            {
                WriteLine($"Task 1 count number {i}");
            }
        }

        static void Task2()
        {
            for (int i = 1; i <= 10; i++)
            {
                WriteLine($"Task 2 count number {i}");
            }
        }
    }
}

When we run the application and we found the output similar to the following images. The output is as simple as first Task 1 completes then Task 2 starts and completes its task. But this is not good appraoch. 

Threading Task Example 

So, let try to implement the threading and modify this program so that it can work in parallel mode. First we will create two threads and associate these methods to them as follows in Main method. After completing this, let start the thread using Start() method.

static void Main(string[] args)
{
    Thread objTask1 = new Thread(Task1);
    Thread objTask2 = new Thread(Task2);

    // Run the task 1
    objTask1.Start();

    // Run the task 2            
    objTask2.Start();

    ReadLine();
}

If you run the program, you will find that your tasks are performing parallel as you can see in the images as follows.

Thread Task

If you have a scenario, where you would like to continue your work and halt to other threads. So, we have JOIN method for the thread, which basically stop the execution of other threads untill the current thread does not complete its task.

using System;
using System.Threading;
using static System.Console;

namespace ThreadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread objTask1 = new Thread(Task1);
            Thread objTask2 = new Thread(Task2);

            // Run the task 1
            objTask1.Start();
            objTask1.Join();

            // Run the task 2            
            objTask2.Start();

            ReadLine();
        }

        static void Task1()
        {
            for (int i = 1; i <= 10; i++)
            {
                Write($"{i} ");
            }
        }

        static void Task2()
        {
            for (int i = 1; i <= 10; i++)
            {
                Write($"{i} ");
            }
        }
    }
}

If you run the program then you will find that first your task 1 is being complete and the other will start.

1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

We have a couple of scenarios, where we would like to stop thread execution or task process for a couple of seconds or for sometimes. So, we can do it with Thread.Sleep(). Sleep()  method basically takes an argument as a time.

using System;
using System.Threading;
using static System.Console;

namespace ThreadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread objTask1 = new Thread(Task1);
            Thread objTask2 = new Thread(Task2);

            // Run the task 1
            objTask1.Start();            
           

            // Run the task 2            
            objTask2.Start();

            ReadLine();
        }

        static void Task1()
        {
            for (int i = 1; i <= 10; i++)
            {
                Write($"{i} ");
                Thread.Sleep(1000);
            }
        }

        static void Task2()
        {
            for (int i = 1; i <= 10; i++)
            {
                Write($"{i} ");
                Thread.Sleep(500);
            }
        }
    }
}


Once you run the program, you will see, it will stop after printing a number and wait for 500 or 1000 milliseconds as per the tasks.

1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 6 7 8 9 10

Conclusion

So, today we have learned basic about threading in csharp, why it is required and how to use it in csharp program.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks