Types of Threads in C#
Multi-threading is the most useful feature of C# which allows concurrent programming of two or more parts of the program for maximizing the utilization of the CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process. C# supports two types of threads are as follows :
A thread which keeps on running to complete its work even if the Main thread leaves its process, this type of thread is known as foreground thread. Foreground thread does not care whether the main thread is alive or not, it completes only when it finishes its assigned work. Or in other words, the life of the foreground thread does not depend upon the main thread.
Main Thread Ends!! mythread is in progress!! mythread is in progress!! mythread is in progress!! mythread is in progress!! mythread ends!!
Explanation: In the above example, thr thread runs after main thread ended. So, the life of thr thread doesn’t depend upon the life of the main thread. The thr thread only ends its process when it completes its assigned task.
A thread which leaves its process when the Main method leaves its process, these types of the thread are known as the background threads. Or in other words, the life of the background thread depends upon the life of the main thread. If the main thread finishes its process, then background thread also ends its process.
Note: If you want to use a background thread in your program, then set the value of IsBackground property of the thread to true.
In progress thread is: Mythread Main Thread Ends!!
Explanation: In the above example, IsBackground property of Thread class is used to set the thr thread as a background thread by making the value of IsBackground true. If you set the value of IsBackground false, then the given thread behaves as a foreground Thread. Now, the process of the thr thread ends when the process of the main thread ends.