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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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. 

Looking to accelerate your career as a skilled Full Stack Web Developer? Leverage Caltech CTME's academic excellence in a unique bootcamp-style Post Graduate Program in Full Stack Web Development. Enroll Now!

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.

Simplilearn is the world's most popular online Bootcamp for learning digital economy skills, and it's here to help you do that. Digital marketing and data science are just a few subjects you will cover in-depth in the online courses.

You've come to the right place if you're interested in learning more about software development and working in the field. The Caltech CTME and the Indian Institute of Technology, Kanpur, have collaborated with Simplilearn to deliver their Software Development courses. In addition to more advanced topics like Competitive Programming, these courses teach the fundamentals of data structures and algorithms. As a software developer, data structures, including trees, graphs, and queues, will be taught to you.

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

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

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