Threading is a concept we all knows and most of us would have been implemented it in the real world applications. I would like to inform about one more inner level detail on threads – that is Foreground and Background threads.
Types of Threads
Basically, there are two types of threads which fall into:
- Foreground Thread
- Background Thread
Foreground threads are threads which will continue to run until the last foreground thread is terminated. In another way, the application is closed when all the foreground threads are stopped.
So the application won’t wait until the background threads are completed, but it will wait until all the foreground threads are terminated.
By default, the threads are foreground threads. So when we create a thread the default value of IsBackground property would be false.
Background threads are threads which will get terminated when all foreground threads are closed. The application won’t wait for them to be completed.
We can create a background thread like following:
Thread backgroundThread = new Thread(threadStart);
backgroundThread.IsBackground = true;
We can see the difference by using a windows or console application. In the attachment, I have provided such an application. The application is explained below:
The application contains 2 buttons, on click of each it will create a thread.
Each thread will be executing a method which takes 25 seconds to execute through a mere Thread.Sleep() invoke.
private void TenSecondsMethod()
// Method of 25 seconds delay
The first one will be Background thread and second would be Foreground.
After clicking each button, you can try closing the application.
From the windows task manager we can see the application would not be listed in the case of Background thread created.
From the windows task manager we can see the application would be still running in the case of Foreground thread created.
The following image shows the snapshot of task manager just after closing the application after invoking a foreground thread. The application will continue to run until all the foreground threads are completed.
We can specify foreground threads for business critical tasks.
Meantime, the background threads can be useful for polling services or logging services which could be discontinued once the application is closed.