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.
Related
When all foreground threads are gone, CLR stops the background threads. That can be read a lot. But what I want to know is how the background thread or the application can detect this situation.
Why? I consider it a bad style to let background threads be killed automatically by some CLR magic, so I normally write code to ensure that a thread gets terminated in a ordered way. But failing to do so, would hang the application in the process of being terminated. So I am considering to mark my worker threads as "background", to avoid the hang, but I still want to know that it happens, so that I can fix that bug.
Is there some equivalent to a ThreadAbortException that I can catch in the thread main method or some handler I can register?
Help with ideas for redesign of the below C# program would be greatly appreciated. I am trying to pick between implementing multithreading using 1) TAP, 2) course-grained threads that contain spinners that terminate when their bools are set to false, or 3) the same threads using signalling instead of these bools. I will explain the program below, to make the case clear.
The Program
The program is a game automation application in C# that I am developing as a fun way to learn the language and C# (5.0) features better. It has a UI that needs to remain responsive while the app runs.
When a particular tab in the UI is opened, the program fires up a new thread called "Scan" that, in a new method in another class, scans various memory locations and updates labels in the UI with these quickly changing values using the UI's SynchronizationContext. This goes on in a while(scanning) loop, for as long as scanning bool is true (usually the full life-duration of the program).
When the user clicks the Start button on this tab, the program fires up two new threads that does the following: Thread "Run" moves the character around following a particular path. Thread "Action" hits particular buttons and performs actions at the same time as the player runs the path. If a certain scenario occurs, the program should stop the running thread and the action thread temporarily, run a method, and when it finishes, go back to the running and action'ing.
When the user clicks the Stop button on this tab, the automation should halt and threads terminate.
The Challenge
I have already created a working version using continuous spinner loops in each thread that takes care of the various work. The spinners run using a while(myBool). For the three threads the bools are: scanning, running and actioning.
When I want to stop a thread I set the bool to false, and use a Thread.Join to wait for the thread to terminate gracefully before proceeding. The threads can, as mentioned, be stopped by the user clicking the Stop button, or automatically by the program as part of its functionality. In the latter case a thread is stopped, Joined, and then at a later stage restarted.
After having done a lot of reading and research on threading and the new async programming tools in C# 5.0, I have realized that the way I am currently doing it might be very clumsy and unprofessional. It creates lots of synchronization/thread-safety issues, and as the goal of all of this is to learn more about C# I wanted to get your take on whether I should change it to a fine-grained asynchrounous programming approach instead, using TAP with async and await as appropriate.
Does this sound like a case where Tasks with cancellation tokens could be useful? The threads are after all long-running operations, so I was concerned that using the thread pool (Task.Run) would cause bad hygiene in the thread pool (over-subscription). If async programming seems like a bad match here, what about using threads as I have done, but instead use signalling to start and stop the threads?
Any thoughts greatly appreciated.
No. TPL was designed to run shorter tasks where the allocation of new threads all time would hurt perfomance. It got quite nice features like job queues and work stealing (a TPL thread can take jobs from another thread). It can of course have longer running task, but you wont get so many benefits from that. On the contrarary, you force TPL to allocate new threads.
However, the question is a bit general in the sense that we need more information about your actual implementation to know what you should use. For the Scan thread it's quite obvious that it should run in a single thread.
But for the others it's hard to know. Do they do work all the time or periodically? If they do work all the time you should keep them in seperate threads.
As for the thread syncronization there is another alternative. You could use a ConcurrentQueue to queue up everything that has to be drawn. In that way you do not need any synchronization. Just let the UI thread check the queue and draw anything in it, while the producers can continue to do their work.
In fact, in that way you can move anything not related to UI drawing to other threads. That should also improve the responsiveness in your application.
public void ActionRunnerThreadFunc()
{
_drawQueue.Enqueue(new SpaceShipRenderer(x, y));
}
public void UIThreadFunc()
{
IItemRender item;
if (_drawQueue.TryDequeue(out item))
item.Draw(drawContext);
}
I'm doing all this in C#, in Visual Studio 2008.
I want to slow down the work of my algorithm so that the user can watch it's work. There is a periodic change visible at the GUI so I added Thread.Sleep after every instance.
Problem is that Thread.Sleep, when set to at least a second, after a few instances of Thread.Sleep (after few loops) simply freezes entire GUI and keeps it that way till program completion. Not right away, but it always happens. How soon depends on the length of the sleep.
I have proof that entire program does not freeze, it's working it's thing, even the sleep is making pauses of correct length. But the GUI freezes at certain point until the algorithm ends, at which point it shows the correct final state.
How to solve this issue? Alternative to pausing algorithm at certain point?
First off, don't make the user wait for work that is done before they even think about when it will be finished. Its pointless. Please, just say no.
Second, you're "sleeping" the UI thread. That's why the UI thread is "locking up." The UI thread cannot be blocked; if it is, the UI thread cannot update controls on your forms and respond to system messages. Responding to system messages is an important task of the UI thread; failing to do so makes your application appear locked up to the System. Not a good thing.
If you want to accomplish this (please don't) just create a Timer when you start doing work that, when it Ticks, indicates its time to stop pretending to do work.
Again, please don't do this.
I'd guess everything is running out of a single thread. The user probably invokes this algorithm by clicking on a button, or some such. This is handled by your main thread's message queue. Until this event handler returns, your app's GUI cannot update. It needs the message queue to be pumped on regular basis in order to stay responsive.
Sleeping is almost never a good idea, and definitely not a good idea in the GUI thread. I'm not going to recommend that you continue to use sleep and make your GUI responsive by calling Application.DoEvents.
Instead, you should run this algorithm in a background thread and when it completes it should signal so to the main thread.
You are about to commit some fairly common user interface bloopers:
Don't spam the user with minutiae, she's only interested in the result
Don't force the user to work as fast as you demand
Don't forbid the user to interact with your program when you are busy.
Instead:
Display results in a gadget like a ListBox to allow the user to review results at her pace
Keep a user interface interactive by using threads
Slow down time for your own benefit with a debugger
This depends on a lot of things, so its hard to give a concrete answer from what you've said. Still, here are some matters that might be relevant:
Are you doing this on a UI thread (e.g. the thread the form-button or UI event that triggered the work started on)? If so, it may be better to create a new thread to perform the work.
Why do you sleep at all? If the state related to the ongoing work is available to all relevant threads, can the observer not just observe this without the working thread sleeping? Perhaps the working thread could write an indicator of the current progress to a volatile or locked variable (it must be locked if it's larger than pointer size - e.g. int or an object - but not otherwise. If not locked, then being volatile will prevent cache inconsistency between CPUs, though this may not be a big deal). In this case you could have a forms timer (there are different timers in .Net with different purposes) check the status of that variable and update the UI to reflect the work being done, without the working thread needing to do anything. At most it may be beneficial to Yield() in the working thread on occasion, but its not likely that even this will be needed.
I am using .NET 3.5 and am trying to wrap my head around a problem (not being a supreme threading expert bear with me).
I have a windows service which has a very intensive process that is always running, I have put this process onto a separate thread so that the main thread of my service can handle operational tasks - i.e., service audit cycles, handling configuration changes, etc, etc.
I'm starting the thread via the typical ThreadStart to a method which kicks the process off - call it workerthread.
On this workerthread I am sending data to another server, as is expected the server reboots every now and again and connection is lost and I need to re-establish the connection (I am notified by the lost of connection via an event). From here I do my reconnect logic and I am back in and running, however what I easily started to notice to happen was that I was creating this worker thread over and over again each time (not what I want).
Now I could kill the workerthread when I lose the connection and start a new one but this seems like a waste of resources.
What I really want to do, is marshal the call (i.e., my thread start method) back to the thread that is still in memory although not doing anything.
Please post any examples or docs you have that would be of use.
Thanks.
You should avoid killing the worker thread. When you forcibly kill a Win32 thread, not all of its resources are fully recovered. I believe the reserved virtual address space (or is it the root page?) for the thread stack is not recovered when a Win32 thread is killed. It may not be much, but in a long-running server service process, it will add up over time and eventually bring down your service.
If the thread is allowed to exit its threadproc to terminate normally, all the resources are recovered.
If the background thread will be running continuously (not sleeping), you could just use a global boolean flag to communicate state between the main thread and the background thread. As long as the background thread checks this global flag periodically. If the flag is set, the thread can shut itself down cleanly and exit. No need for locking semantics if the main thread is the only writer and the background thread only reads the flag value.
When the background thread loses the connection to the server that it's sending data to, why doesn't it perform the reconnect on its own? It's not clear to me why the main thread needs to tear down the background thread to start another.
You can use the Singleton pattern. In your case, make the connection a static object. Both threads can access the object, which means construct it and use it.
The main thread could construct it whenever required, and the worker thread access it whenever it is available.
Call the method using ThreadPool.QueueUserWorkItem instead. This method grabs a thread from the thread pool and kicks off a method. It appears to be ideal for the task of starting a method on another thread.
Also, when you say "typical ThreadStart" do you mean you're creating and starting a new Thread with a ThreadStart parameter, or you're creating a ThreadStart and calling Invoke on it?
Have you considered a BackgroundWorker?
From what I understand, you just have a single thread that's doing work, unless the need arises where you have to cancel it's processing.
I would kill (but end gracefully if possible) the worker thread anyway. Everything gets garbage-collected, and you can start from scratch.
How often does this server reboot happen? If it happens often enough for resources to be a problem, it's probably happening too often.
The BackgroundWorker is a bit slower than using plain threads, but it has the option of supporting the CancelAsync method.
Basically, BackgroundWorker is a wrapper around a worker thread with some extra options and events.
The CancelAsync method only works when WorkerSupportsCancellation is set.
When CancelAsync is called, CancellationPending is set.
The worker thread should periodically check CancellationPending to see if needs to quit prematurely.
--jeroen
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.