Now let’s replace DoSomeHeavyLifting method call in the Main method with a new code that creates a new thread. This makes an application more responsive and use friendly. Multithreading, or simply threading, allows us to create secondary threads that may be used to execute time-consuming background tasks and leave the primary thread available to the main program. Multiple threads or multithreading is the solution for this problem.
How about a Windows application that has a method that takes longer and the user has to wait to do anything else? What if there is a function that needs even longer background work? For example, creating a report and printing it. In this case, the DoSomething method has to wait until the DoSomeHeavyLifting method is executed. After that, the DoSomething method is called. In Listing 1, the DoSomeHeavyLifting is the first method being called that takes about 4 seconds.
// This method doesn't take anytime at all.// This method takes 4 seconds to finish.// This is the entry point of a C# program.Let’s take an example of code in Listing 1. The code in the Main method is executed in a linear fashion in a single, primary thread. The Main method is the entry point of a C# program. The entry point of a C# program starts in the Main method and that is the path of the primary thread. That means, only one path of the code is executed at a time by the main or primary thread. Additionally, a program can use the ThreadPool class to execute code on worker threads that are managed by the CLR.Ī C# program is single threaded by design. Along with this main thread, a process can create one or more threads to execute a portion of the code. This thread is called primary or main thread. NET Core application, the CLR creates a single foreground thread to execute application code via the Main method. NET Core, the common language runtime (CLR) plays a major role in creating and managing threads lifecycle. 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. Every process contains at least one primary thread which takes care of the entry point of the application execution. 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.