In CLR, what is difference between a background and foreground thread? - c#

What is difference between a background and foreground thread ?

See this page:
Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.

From MSDN:
Background threads are identical to
foreground threads with one exception:
a background thread does not keep the
managed execution environment running.

By default, threads are foreground threads, meaning they keep the application alive for as long as
any one of them is running. C# also supports background threads, which don’t keep the
application alive on their own – terminating immediately once all foreground threads have ended.

There are two types of threads -
Foreground Thread
Background Thread
Whenever we open any application, then the main UI thread is of type Foreground thread. This is the default thread type. Suppose when we create any new thread. By default, the thread current type is foreground itself. If you want to change the type of the thread you will have to execute threadName.IsBackground = true;.
Now the main story starts. What is the difference? And why do we need these two types?
Foreground Thread: Suppose we are creating a thread ThreadA. If we need the thread ThreadA to keep executing in spite of all other threads are aborted, even if our main UI thread is no more alive, then in this case we must keep our thread type Foreground. So if you keep your thread foreground type, then even if you close your application, the foreground thread ThreadA will keep running. You can track it also in your task manager.
Background Threads: Now if you change your thread type to be background thread, then this thread is going to be dependent on other foreground threads. Because In the case if none of the thread of type foreground is running anymore, then all the background thread will have to be forcefully aborted.

The important difference between background and foreground threads that is not mentioned yet is the following: a background thread executes only when the number of foreground threads executing is smaller than the number of processors MSDN.

Background thread is going to be killed no matter if it's not finished yet when there will be no active foreground threads.
An example of foreground thread is Application Main thread.
Background thread examples are:
System.Threading.Task class
System.Threading.ThreadPool class
For more information, check out out this MSDN article.

If any of the foreground or background threads terminate, the application dies immediately. It is possible to change the thread from foreground to background and vice versa at any time during application lifetime. CLR creates two kinds of threads to better support AppDomain. CLR will forcibly end any background threads that are running if the foreground thread terminates. Any threads created by native code that enter the managed execution environment are marked as background threads.

Related

Does background thread run on lower priority than foreground thread?

Does background thread run on lower priority than foreground thread even though their Thread.Priority is set to same value?
Consider code below: -
Thread threadFG = new Thread(MyMethod);//foreground thread
Thread threadBG = new Thread(MyMethod);//background thread
threadBG.IsBackground = true;
Will there be a difference in performance? Note that I am using default priority for both the threads.
Lot many articles on web including MSDN say that background thread will automatically destroy on application exit which is not the case with foreground thread. Lot many questions on StackOverflow say the same. But I do not found a resource that talk about performance difference between two.
Just because background thread, will that thread run slower than foreground thread?
Does background thread run on lower priority than foreground thread even though their Thread.Priority is set to same value?
No. Unless explicitly assigned, all threads start with default priority e.g. Normal
Will there be a difference in performance?
Measure it yourself, use stopwatch or similar mechanism to measure performance. Execution performance of threads rely on many things including host computer's components (CPU architecture, number of cores etc.).
Just because background thread, will that thread run slower than foreground thread?
No. As #Damien_The_Unbeliever's MSDN link explains: Foreground or Background has nothing to do with performance.

How to kill application completely regardless thread

My application on startup may start a few thread concurrently. Now based on some condition I would like to completely kill off all the thread regardless the state of other threads.
I have tried App.Current.ShutDown() as well as Application.Current.ShutDown but doesn't work?
You can try
Environment.Exit(0);
You can replace 0 with any code you want from here
You should see Killing all threads that opened by application (and Shutting down a multithreaded application consequently) as I think he provides some solid advice.
A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.
Set your thread's property IsBackground=true
var t= new Thread();
t.IsBackground = true;
Also See this:
How to: Create and Terminate Threads (C# Programming Guide)
If you need to kill the running application, regardless of state you can either use
Environment.Exit(0); // use -1 if you're exiting with an error, exiting with 0 is considered to have exited without errors.
Or if you really want to use the hammer
Environment.FailFast()
FailFast's documentation says:
Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message in error reporting to Microsoft.
Use the FailFast method instead of the Exit method to terminate your application if the state of your application is damaged beyond repair, and executing your application's try/finally blocks and finalizers will corrupt program resources.
If your other threads are background threads they will end (i.e. abort silently when you shutdown the WPF application which is running on the only foreground thread):
From MSDN:
"...background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete."
e.g.
Thread myThread = new Thread();
myThread.IsBackground = true;
ThreadPool threads background ones.

Background Thread And Foreground Thread

I have an monitoring application that will have multiple threads constantly monitoring the CPU usage, memory usage, hard disk usage, etc. I create a separate thread to monitor each of this and it keeps on running under the while loop get the values for the same.
Now my question is what happens if I keep thread.IsBackGround = true and what happens if I keep thread.IsBackGround = false?
I know the difference between foreground and background thread. But I am not able get what would be the better for me to use. If I have multiple foreground threads running then if I stop the application will all foreground threads stop automatically? or I need to explicitly stop them?
In case background threads, those will be aborted by the system.

Background thread vs UI thread

Could any one help me to figure out background thread and UI thread in C#.I have googled it but i coudnt find article illustrate both.
A UI thread creates UI elements and waits and responds to events like mouse clicks and key presses. You can only access the UI elements from the UI thread.
There are two types of threads: background and foreground. A UI thread is an example of a foreground thread.
The difference between background and foreground threads is pretty simple. Background threads don't stop a process from terminating, but foreground threads do. When the last foreground thread stops, then all the background threads are also stopped and the process ends.
This website has a lot of information about threading as well as parallel programming: http://www.albahari.com/threading/
Good luck
There is another key issue to keep in mind. There is a single U.I. thread and you can only call methods on U.I. objects in that thread. In another thread you need to call Control.Invoke() to flip to the U.I. thread if you are doing something like update a status bar.

Find the foreground thread from the background thread

When you are in the context of the background thread.
Thread.IsBackground == true
There is a way to find the foreground thread calling this background thread ?
Thanks for your help
Update: The thread created are background and handled by a threadpool (Inside the Workflow Foundation Runtime). I have no way to add the reference from the main thread inside each background thread. There is no way to find that foreground thread from the threadpool ?
There's no such relationship. Any thread can create a new thread, including another background thread. After the new thread has been created, there's no relationship between the creating thread and the new thread. If you need to know which thread created the new thread, you'll need to pass that information in the ThreadStart.
EDIT: For thread-pool threads, by the time any of your code is running I assume it's been specified by you as a task somewhere, in some way. If you need some information to be available (whether that's a thread ID or anything else) you need to put it in the context for that task.

Categories