Background Thread And Foreground Thread - c#

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.

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.

Main Thread is Foreground thread or Background thread?

The .NET Framework defines two types of threads: foreground and background.
By default when we create a thread, it is a foreground thread, but we can change it to a background
All processes have at least one thread of execution, which is usually called the main thread because it is the one that is executed when your program begins.
Is this main thread is back ground or foreground thread.
It is really rather best that you completely dismiss the concept of a "foreground thread". The CLR has no notion of it and does not treat the startup thread of program special in any way. It is just a "normal" thread, no different from any other thread you create with the Thread class. The notion that a "foreground thread" is important because it is doing the most visible and most "important" job is sometimes true but not always. Not in a service or a Modern UI app for example, it is worker thread that does the heavy lifting in them. It is true-ish in a console, Winforms or WPF app.
The concept is only truly valid in legacy runtime environments, like those of a C or C++ program. Their execution model dates from the 1970s, operating systems did not support threads back then. Specific in such legacy runtime environments is that the program always terminates when the startup thread ends, regardless of what other threads are running. This is not the way the CLR works, it thinks those other threads are just as important. Of course they are.
Still thinking of the concept of a "background thread" is okay. A threadpool thread is certainly backgroundish. Their IsBackground property is always true. Something you can change btw, you can simply set it to false and the CLR doesn't treat it like a background thread anymore. But you can't change its ApartmentState, it is always MTA and that makes them fundamentally unsuitable to display any user interface. In other words, you can never see them :)
The most important attribute of a background thread is that you can treat them like little soldiers that you don't mind getting killed in the line of duty. Randomly and without any notification and the expectation of no dire consequences. Pretty important that they do a non-critical job of course. It already gets iffy if, for example, you let such a thread write a file. That's going to leave a half-written file behind when the soldier gets shot. That has a knack of causing trouble later, another program reading that file is going to malfunction. A network or dbase connection is typical for a background thread. The software on the other end of the wire will detect that the connection was lost. It can't otherwise tell the difference between a hard program crash and a normal exit. Tends to end up okay, usually, such software was written to deal with that.
Long story short, only the IsBackground property matters. When a thread exits, the CLR iterates the remaining threads that are still running. If any of them have IsBackground = false then the process keeps running. If not, the CLR will unload the primary AppDomain. Which gets any soldiers shot with a rude abort.
The whole purpose of background threads is that the process will exit if the only threads left executing are background threads.
The main thread needs to be a foreground thread, or the app would just immediately exit.

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.

How to Monitor C# Threads from another Thread

I have several Threads running in a ThreadPool in my WPF App. I need to monitor them, possibly from another Thread to find out if all of those Threads have terminated.
How would I be able to achieve this.
For simplicity, my usage scenario is:
Click a button
Start several Threads in a ThreadPool.
Start another Thread to Monitor those in a ThreadPool
Lock UI of WPF App.
Release Lock when the Thread in step 3 sets a Global value to indicate that Threads started in (2) have terminated.
Put all the threads in the threadpool in an array. When you want to wait for the pool threads to exit, use WaitHandle.WaitAll to wait for the threads to complete.
The problem at hand is actually too localized. I had to adopt to an Ad Hoc approach to fit in with the initial flawed design.
My approach was to simply increase a counter whenever a Thread is started and decrease the value of the counter when that Thread terminates. To watch over the value of counter, I initiated another Thread simply to monitor the value of counter. Maybe not an elegant approach, but seems to work fine.

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

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.

Categories