What is multithreading in C#?

Alex Rivers

A thread in C# is a path of execution of a program and every thread in a program has a different path that performs different tasks. Threads are also called lightweight processes. So, in short, each program that is running on your system is a process and for the code to work inside the application, a process uses a term known as a thread. It helps in avoiding the wastage of CPU cycles.

The process of these threads performing multiple tasks simultaneously is what is known as multithreading. For example, on macOS, several programs can run at the same time like Safari, FaceTime, Calculator, Notes, etc.

Multithreading in C#

The process of multithreading contains multiple threads in one process. Every thread performs a different activity. Let’s say we call a class that has three different methods in it. With multithreading, every method is executed by a separate thread and works simultaneously. Thus, multiple tasks happen at the same time.

I. Thread Life Cycle

The cycle begins when System.Threading.Thread object is created and keeps working until the cycle comes to an end.

Here is a list of states that happen during a thread’s life cycle:

1. The Unstarted State

This happens when the instance of a thread is created but the Start method has not begun.

2. The Ready State

This happens when the thread is ready to run.

3. The Not Runnable State

A thread is said to be ‘not runnable’ when the following happens:

  1. The sleep method was called
  2. The wait method was called
  3. I/O operations blocked it

4. The Dead State

This happens when the thread has completed execution or gets aborted.

II. The Main Thread in C#

The Main Thread is that thread that every program carries by default. It executes the logic of the program. This means that every program is single-threaded by default. This can be a problem because it means that while one process is working, the other process has to wait for the first one to stop so that it can get executed.

Now, in C#, the System Thread class is used for creating and accessing the other single threads. The first thread to be executed is the main thread. It automatically gets created when the execution begins. Threads created from the Thread class are known as the Child threads of the main thread.

Current Thread helps you in accessing a thread.

Here is a program that will make you understand how single-threading works:


using System;
using System.Threading;
  
public class Program {
  
    public static void sample1()
    {

        for (int i = 0; i <= 10; i++) {
  
            Console.WriteLine("Sample 1 is : {0}", i);
            if (i == 5) {
                Thread.Sleep(8000);        
            }
        }
    }
  
    public static void sample2()
    {
        for (int j = 0; j <= 10; j++) {
  
            Console.WriteLine("Sample 2 is : {0}", j);
        }
    }
}

public class Example {
  
    static public void Main()
    {
 
        Program.sample1();
        Program.sample2();
    }
}

The Output will be:

Sample 1 is : 0
Sample 1 is : 1
Sample 1 is : 2
Sample 1 is : 3
Sample 1 is : 4
Sample 1 is : 5
Sample 1 is : 6
Sample 1 is : 7
Sample 1 is : 8
Sample 1 is : 9
Sample 1 is : 10
Sample 2 is : 0
Sample 2 is : 1
Sample 2 is : 2
Sample 2 is : 3
Sample 2 is : 4
Sample 2 is : 5
Sample 2 is : 6
Sample 2 is : 7
Sample 2 is : 8
Sample 2 is : 9
Sample 2 is : 10

In the program above, Sample 1 is under execution. While Sample 1 is under process, Sample 2 waits. Sample 2 begins once Sample 1 finishes its execution. Hence, multithreading is necessary to evade the problems that arise in single-threading.

Here is a program that performs multithreading:

using System;
using System.Threading;
  
public class Sample {
  
    public static void sample1()
    {
  
        // It prints numbers from 0 to 10
        for (int i = 0; i <= 10; i++) {
            Console.WriteLine("Sample 1 is : {0}", i);
            if (i == 5) {
                Thread.Sleep(8000);
            }
        }
    }
  
    public static void sample2()
    {
        for (int j = 0; j <= 10; j++) {
            Console.WriteLine("Sample 2 is : {0}", j);
        }
    }
  
    static public void Main()
    {
  
        Thread thd1 = new Thread(sample1);
        Thread thd2 = new Thread(sample2);
        thd1.Start();
        thd2.Start();
    }
}

Here is what the output will look like:

Sample 1 is : 0
Sample 1 is : 1
Sample 1 is : 2
Sample 1 is : 3
Sample 1 is : 0
Sample 1 is : 1
Sample 1 is : 2
Sample 1 is : 3
Sample 1 is : 4
Sample 1 is : 5
Sample 1 is : 6
Sample 2 is : 7
Sample 2 is : 8
Sample 2 is : 9
Sample 2 is : 10
Sample 2 is : 4
Sample 2 is : 5
Sample 2 is : 6
Sample 2 is : 7
Sample 2 is : 8
Sample 2 is : 9
Sample 2 is : 10

However, this method will be better because both the threads will be executed together as they are functioning at the same time. Note that the outputs here are different.

C#

Properties and their Description

Serial no.Property & Description
1Name Gets or sets the name of the thread.
2CurrentCulture Gets or sets the culture for the current thread.
3CurrentPrinciple Gets or sets the thread’s current principal.
4CurrentThread Gets the currently running thread.
5CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time.
6IsAlive Gets a value indicating the execution status of the current thread.
7ManagedThreadId Gets a unique identifier for the currently managed thread.
8IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
9IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
10ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
11Priority Gets or sets a value indicating the scheduling priority of a thread.
12CurrentContext Gets the current context in which the thread is executing.

III. Benefits of Multithreading

  • It runs numerous processes concurrently.
  • Sharing of time between various processes is better.
  • Thread synchronization functions can be used to provide enhanced process-to-process communication.
  • It helps in maximizing the use of the CPU’s capabilities as system resources are barely impacted by threads.
  • It has helped many C# programmers to execute reliable codes and has made their job smooth and easy.

Conclusion

We discussed how multithreading is helpful in C# and how it can save time and make multiple threads run simultaneously, making it an efficient method for C# programming.

Happy Coding!

Also Read: What Should I Learn After JavaScript?

Leave a Comment