A One-Stop Solution to C# Threads With a Guide and Examples

Multitasking refers to the act of performing several tasks or activities at the same time. As an example of multitasking, the Windows operating system may run many applications concurrently, such as Google Chrome, Notepad, and MS Office. The operating system employs the concept of a process to run all of these programs simultaneously. 

In this 'C# Threads' tutorial, you will learn the major technical aspects of Thread class and the fundamentals involving Multithreading.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is a C# Threads Class?

Threads-thread-img1

The term "thread" refers to a program's execution path. The control flow of each thread is unique. Threading decreases the number of wasted CPU cycles and enhances the overall performance of a program. New threads are created with the help of the thread class. 

The thread class is used to specify a thread's priority. The current status of a thread is also displayed.

You can now go on to the next chapter to learn about the Thread Life-Cycle now that you have a basic knowledge of the definition of C# Threads.

Thread Life-Cycle

Threads-Lifecycle-img1

Generally, a thread's life cycle starts with the instantiation of an object of the "System.Threading" Thread class ends whenever the thread is suspended or completes its processing.

There are four states of a Thread Life-Cycle, they are as follows:

  • Unstarted State

It happens when a thread object is created, but the Start method is not called.

  • Ready State

The Ready state indicates that the thread is ready for implementation but is waiting for a CPU loop.

  • Not Runnable State

This is when you have a "not runnable state" and a thread is not executable because of the following:

  • The sleep method has been invoked
  • The wait method has been invoked
  • I/O activities are causing a bottleneck
  • Dead State

It is the state wherein the thread's implementation has finished or has been stopped.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

What Is a Single-Threaded Model? 

Threads-Singlethreaded-img1

The Main Thread is the primary thread in any program that executes the logic of the program. As a result, by nature, all programs and applications are single-threaded. This single-threaded design has a drawback. The single thread synchronizes the execution of the program's processes, meaning that each one is completed sequentially. Because of the delay in processing the first step, the subsequent process is slower.

So far, you have learned about the Threads and the Single-threaded model. Now you will explore the practical implementation of the Single-threaded model.

Implementation of Single-Threaded Model

Now, open the visual studio code and write a code to demonstrate the single-threaded model.

Code: 

using System;

using System.Threading;

namespace Threaddemo

{

    public class mainthread1 {

    // static method one

    public static void thrd1()

    {

        // It prints numbers from 0 to 10

        for (int t = 0; t <= 10; t++) { 

            Console.WriteLine("Thread1 is : {0}", t);

            // When the value of t is equal to

            // 5 then this method sleeps for

            // 5 seconds and after 5 seconds

            // it resumes its working

            if (t == 5) {

                Thread.Sleep(5000);

            }

        }

    }

    // static method two

    public static void thrd2()

    {

        // It prints numbers from 0 to 10

        for (int p = 0; p <= 10; p++) {

            Console.WriteLine("Thread2 is : {0}", p);

        }

    }

// Driver Class

public class mainthread2 { 

    // Main Method

    static public void Main()

    {

        // Calling static methods

        mainthread1.thrd1();

        mainthread1.thrd2();

    }

}

}

Now, go ahead and run it.

Threads-Singlethreaded-implement-img1

Now it went to sleep for 5 seconds after t=5.

Threads-Singlethreaded-implement-img2

Now let's discuss the Multi-threaded model to overcome the drawbacks of the single-threaded model.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is a Multi-Threaded Model? 

Threads-multithreaded-img1.

Multithreading is the utilization of several threads within a single task. Each thread has a distinct purpose. Therefore, the key benefit of Multithreading is that it functions simultaneously, allowing several tasks to be executed simultaneously. Additionally, Multithreading enhances CPU resource use.

So far, you learned about the Single-threaded and Multi-threaded models. Now you will look at the practical implementation of the Multi-threaded model.

Implementation of Multi-Threaded Model

Now, it’s time to open your visual studio code and write a code to demonstrate the single-threaded model.

Code: 

// C# program to illustrate the

// concept of Multithreading

using System;

using System.Threading;

public class mainthread {

    // static method one

    public static void thrd1()

    {

        // It prints numbers from 0 to 10

        for (int x = 0; x <= 10; x++) {

            Console.WriteLine("Thread1 is : {0}", x);

            // When the x's value is equal to 5 then

            // this method sleeps for 5 seconds

            if (x == 5) {

                Thread.Sleep(5000);

            }

        }

    }

    // static method two

    public static void thrd2()

    {

        // It prints numbers from 0 to 10

        for (int y = 0; y <= 10; y++) {

            Console.WriteLine("Thread2 is : {0}", y);

        }

    }

    // Main Method

    static public void Main()

    {

        // Creating and initializing threads

        Thread t1 = new Thread(thrd1);

        Thread t2 = new Thread(thrd2);

        t1.Start();

        t2.Start();

    }

}

Threads-Multithreaded-implement-img1.

By now, you must have a good knowledge and command of the technical aspects of C# Threads and multithreading. 

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

The next lesson in your C# training can be "Operators and Expressions in C#". There are a variety of symbols that are used to do a variety of functions, including operators. Variables and values are nothing new to operators. The combination of operands and operators makes up an expression in C#. At the very least, an expression requires an operand; nonetheless, it can have no operators.

Programming requires understanding C# threads to be effective and responsive. Thanks to this tutorial, you have a strong foundation with real-world examples. Consider enrolling in the Full Stack Developer - MERN Stack course to improve your abilities even more and increase the scope of your job opportunities. Integrating your understanding of full-stack web development with C# is a fantastic method.

The comments section below is open for questions and comments about this 'C# Threads' tutorial. Happy learning!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.