![]() |
VOOZH | about |
Multithreading is one of the core features in C# that allows multiple tasks to be performed concurrently. Threads allow your application to run multiple tasks simultaneously, improving performance, and resource utilization. In C#, there are two types of threads.
Note: When an application starts, it automatically creates a foreground thread, which is the mafin thread of the application. By default, newly created threads are foreground threads. We can change a thread to a background thread by setting its IsBackground property to true.
A foreground thread continues to execute even after the main thread completes its execution. It ensures that the application does not terminate until all foreground threads have completed their assigned tasks. Foreground threads are critical when a task must complete before the application exits.
Example:
Main Thread Ends!! Foreground thread is in progress!! Foreground thread is in progress!! Foreground thread is in progress!! Foreground thread ends!!
Explanation: In the above example, the thread runs after the main thread ends. So, the life of the thread does not depend upon the life of the main thread. The thread only ends its process when it completes its assigned task.
A background thread is terminated as soon as the main thread finishes its execution. The lifespan of a background thread depends on the main thread. These threads are used for non-critical tasks that can be abandoned when the application shuts down.
Note: If we want to use a background thread in our program, then set the value of IsBackground property of the thread to true.
Example:
Background thread is in progress!! Main Thread Ends!!
Explanation: In the above example, the IsBackground property is used to mark the created thread (bt) as a background thread by making the value of IsBackground true. If we set the value of IsBackground to false, then the given thread behaves as a foreground Thread. Now, the process of the third thread ends when the process of the main thread ends.
Feature | Foreground Thread | Background Thread |
|---|---|---|
Lifespan | Independent of the main thread | Dependent on all foreground threads |
Execution | Ensures task completion before application exit | May terminate before task completion |
Use Case | Critical tasks | Non-critical or secondary tasks |
Termination | Explicitly controlled | Automatically terminated with the main thread |