Does background thread run on lower priority than foreground thread? - c#

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.

Related

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.

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.

Is ThreadPool worth it in this scenario?

I have a thread that I fire off every time the user scans a barcode.
Most of the time it is a fairly short running thread. But sometimes it can take a very long time (waiting on a invoke to the GUI thread).
I have read that it may be a good idea to use the ThreadPool for this rather than just creating my own thread for each scan.
But I have also read that if the ThreadPool runs out of threads then it will just wait until some other thread exits (not OK for what I am doing).
So, how likely is it that I am going to run out of threads? And is the benefit of the ThreadPool really worth it? (When I scan it does not seem to take too long for the scan to "run" the thread logic.)
It depends on what you mean by "a very long time" and how common that scenario is.
The MSDN topic "The Managed Thread Pool" offers good guidelines for when not to use thread pool threads:
There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:
You require a foreground thread.
You require a thread to have a particular priority.
You have tasks that cause the thread to block for long periods of time. The
thread pool has a maximum number of
threads, so a large number of blocked
thread pool threads might prevent
tasks from starting.
You need to place threads into a single-threaded apartment. All
ThreadPool threads are in the
multithreaded apartment.
You need to have a stable identity associated with the thread, or to
dedicate a thread to a task.
Since the user will never scan more than one barcode at a time, the memory costs of the threadpool might not be worth it - I'd stick with a single thread just waiting in the background.
The point of the thread pool is to amortize the cost of creating threads, which are not inexpensive to spin up and tear down. If you have a short-running task, the cost of creating/destroying the thread can be a significant portion of the overall run-time. The maximum number of threads in the thread pool depends on the version of the .NET Framework, typically dozens to hundreds per processor. The number of threads is scaled depending on available work.
Will you run out of threads and have to wait for a thread to become available? It depends on your workload. You can get the maximum number of threads available via ThreadPool.GetMaxThreads(). Chances are (based on the description of your problem) that this number is sufficiently high.
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.getmaxthreads.aspx
Another option would be to manage your own pool of scan threads and assign them work rather than creating a new thread for every scan. Personally I would try the threadpool first and only manage your own threads if it proved necessary. Even better, I would look into async programming techniques in .NET. The methods will be run on the thread pool, but give you a much nicer programming experience than manual thread management.
If most of the time it is short running threads you could use the thread pool or a BackgroundWorker which draws threads from the pool.
An advantage I can see in your case is that threadpool class puts an upper limit on the amount of threads that may be active. It depends on the context of your application whether you will exhaust system resources. Exhausting a modern desktop system is VERY hard to do really.
If the software is used in a supermarket till it is highly unlikely that you will have more then 5 barcodes being analysed at the same time. If its run in a back-end server for a whole row of supermarket tills. Then perhaps 30-100 concurrent requests might be active.
With this sort of theory crafting it is highly unlikely that you will run out of threads, even on embedded hardware. If you have a dozen or so requests active at a time, and your code works, it's ok to just leave it as it is.
A thread pool is just an abstraction though, and you could have queue in the middle that queues request onto a thread-pool, in this scenario for the row-of-till example above, I'd feel comfortable queueing 100-1000 requests against a threadpool with 10 threads.
In .net (and on windows in general), the question should always be reversed: "Is creating a new thread worth it in this scenario?"
Creating a new thread is expensive, and doing it over and over again is almost certainly not worth it. The thread pool is cheap, and really should be the first thing you turn to when you need a new thread.
If you decide to spin up a new thread, soon you will start worrying about re-using the thread if it's already running. Then you will start worrying that sometimes the thread is running but it seems to be taking too long, and so you should make a new one. Then you're going to decide to have a thread not exit immediately upon finishing work, but to wait a little while in case new work comes in. And then... bam! You've created your own thread pool. At which point you should just back up and use the system-provided one.
The folks who mentioned that the thread pool might "run out of threads" were well-intentioned, but they did you a disservice. The limit on the number of threads in the thread pool is quite large. If you run into it, you have other problems.
(And, of course, since .net 2.0, you can set the maximum number of threads, so you can tweak the number if you absolutely have to.)
Others have directed you to MSDN: "The Managed Thread Pool". I will repeat that direction, as the article is good, but in my mind does not sell the thread pool hard enough. :)

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.

Changing thread priority to make my program and computer more responsive

I've written a .NET winforms application that uses a secondary thread to do some heavy processing, which communicates it's progress back to the UI thread. Everything works correctly, the form shows the progress, and I've also created a cancel button to interrupt the processing thread. However, when the time consuming process is going the application and my entire computer slows way down. It takes a long time drag windows around, and there is even a significant delay when trying to type letters into notepad.
I'm assuming I need to reduce the priority of the processing thread, and/or increase the priority of the UI thread. Is this right? Right now both threads are Normal priority.
Is it just as easy as the follwing? Or is there something else I should do?
Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
How should I change the priorities? Should I reduce the priority of the processing, or increase the priority of the UI, or both? And to what setting? AboveNormal, or highest?
I dont necessarily think thread priority is your issue (though it could be part of it). Take a look at this SO question: Background Worker Thread Priority.
It is probably overly tight loops in your background thread which are keeping cpu time on that thread. There are several ways to fix it from the brutal (thread sleeps) to the more reasonable (mutexs and events).
You can also try profiling the background thread (either directly, or in a test harness) to see where it is spending the majority of its time, and try to isolate this with async events or similar offloading techniques.
If you want the background thread to not effect the system responsiveness as a whole, you'll need to lower it's priority, most likely by setting it's Priority to BelowNormal.
Otherwise, it will have the same effect you're currently seeing.
That being said, I'd be hesitant to do this in my own code. If your program is run on a system with more processing cores, this will likely not be an issue, and lowering the thread priority (potentially) will cause your algorithm to take longer to process.
You generally want to leave the priority of your main thread alone, and reduce the priority of the processing thread to Idle.
Normally you should set the priority of the worker thread to a nice level (eg the user might want to do someing in another application and even them the worker thread should play nice) even though Windows already boosts the "active" processes thread (the application you have a window with input focus) a little bit so it will feel more responsive. The higher priorities are usually needed when you need to meet some time constraints.

Categories