Introduction to Threads In C# and .NET

As you can see in Figure 1, there are several processes running on my machine and each process has resource allocation and their usages. The resources include CPU, memory, disk space, network, and IO.
Each computer has finite resources such as CPU, memory, disk space, network, and IO. A computer runs several applications simultaneously. Some of these applications are operating-system related, some are services, and some are user applications. Figure 1 categorizes processes in three different categories - Apps, Background processes, and Windows processes. Apps are the foreground apps running on the device. Background processes runs in the background for various applications installed on the device. Windows processes are the processes required to run Windows operating system, such as checking notifications, emails, app updates, resource management, and so on.
Each process on an operating system is contained within its own boundary and the operating system assigns limited resources to each process so it does not affect other processes.
When a new application starts on Windows, it creates a process for the application with a process id and some resources are allocated to this new process. Every process contains at least one primary thread which takes care of the entry point of the application execution. A single thread can have only one path of execution but as mentioned earlier, sometimes you may need multiple paths of execution and that is where threads play a role.
.NET Core and Threads
In .NET Core, the common language runtime (CLR) plays a major role in creating and managing threads lifecycle. In a new .NET Core application, the CLR creates a single foreground thread to execute application code via the Main method. This thread is called a primary or main thread. Along with this main thread, a process can create one or more threads to execute a portion of the code that is not executed by the main thread. Additionally, a program can use the ThreadPool class to execute code on worker threads that are managed by the CLR.
A C# program is single threaded by design. That means, only one path of the code is executed at a time by the main or primary thread. The entry point of a C# program starts in the Main method and that is the path of the primary thread.
Why multiple threads
The Main method is the entry point of a C# program and code in this method is executed in a linear fashion in a single thread, also called the primary thread.
Let’s take an example of code in Listing 1.
- using System;
- class Program {
- // This is the entry point of a C# program
- static void Main(string[] args) {
- // Main execution starts here
- Console.WriteLine("Main thread starts here.");
- // This method takes 4 seconds to finish.
- Program.DoSomeHeavyLifting();
- // This method doesn't take anytime at all.
- Program.DoSomething();
- // Execution ends here
- Console.WriteLine("Main thread ends here.");
- Console.ReadKey();
- }
- public static void DoSomeHeavyLifting() {
- Console.WriteLine("I'm lifting a truck!!");
- Thread.Sleep(1000);
- Console.WriteLine("Tired! Need a 3 sec nap.");
- Thread.Sleep(1000);
- Console.WriteLine("1....");
- Thread.Sleep(1000);
- Console.WriteLine("2....");
- Thread.Sleep(1000);
- Console.WriteLine("3....");
- Console.WriteLine("I'm awake.");
- }
- public static void DoSomething() {
- Console.WriteLine("Hey! DoSomething here!");
- for (int i = 0; i < 20; i++) Console.Write($ "{i} ");
- Console.WriteLine();
- Console.WriteLine("I'm done.");
- }
- }
Listing 1.
In Listing 1, the DoSomeHeavyLifting is the first method being called that takes about 4 seconds. After that, the DoSomething method is called. In this case, the DoSomething method has to wait until the DoSomeHeavyLifting method is executed. What if there is a function that needs even longer background work? For example, creating a report and printing it. How about a Windows application that has a method that takes longer time and a user has to wait to do anything else?
Multiple threads or multithreading is the solution for this problem. Multithreading or simply threading allows us to create secondary threads that may be used to execute time consuming background tasks and let the primary thread be available to the main program. This makes an application more responsive and use friendly.
Now let’s replace DoSomeHeavyLifting method call in the Main method with a new code that creates a new thread. Replace the following code,
- Program.DoSomeHeavyLifting();
With the following code,
- // Create a thread and call a background method
- Thread backgroundThread = new Thread(new ThreadStart(Program.DoSomeHeavyLifting));
- // Start thread
- backgroundThread.Start();
In this code, we have created a new thread object using the Thread class that takes a ThreadStart delegate as a parameter with method, that is executed in the background. Thread.Start() methods starts a new thread. This new thread is called a worker thread or a secondary thread.
Now, no matter how long the worker thread method takes, the main thread code will be executed side by side.
The new Main method is listed in Listing 2.
- static void Main(string[] args) {
- // Main execution starts here
- Console.WriteLine("Main thread starts here.");
- // Create a thread
- Thread backgroundThread = new Thread(new ThreadStart(Program.DoSomeHeavyLifting));
- // Start thread
- backgroundThread.Start();
- // This method doesn't take anytime at all.
- Program.DoSomething();
- // Execution ends here
- Console.WriteLine("Main thread ends here.");
- Console.ReadKey();
- }
Listing 2.
Now, run the program and you will see that there is no delay in executing DoSomething method.
Threads, Resources, and Performance
Keep in mind, creating more threads is not related to processing speed or performance. All threads share the same processor and resources a machine has. In the case of multiple threads, the thread scheduler with help of operating system schedules threads and allocates a time for each thread. But in a single processor machine, only one thread can execute at a time. The rest of the threads have to wait until the processor becomes available. Creating more than a few threads on a single processor machine may create a resource bottleneck if not managed properly. Ideally, you want a couple of threads per processor. In the case of a dual core processor, having 4 threads is ideal. In the case of a quad core processor, you can create up to 8 threads without noticing any issues.
Managing thread resources is also very important for resource hungry apps. If you’ve some background in IO processing and some background database operations, you should manage it so thateach thread works with separate resources.
Similar to a process, threads also run within their own boundaries but they can communicate with each other, share resources, and pass data among them.


Jaydeep PatilPosted Oct 6, 2022, 5:41 PM
Great Content..