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?
Related
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.
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.
I am having an issue where I have a Windows CE compact framework Application written in C#, where I have the primary GUI thread set to normal priority and a communication thread set to above normal priority to get as close to pseudo real time performance. The issue I am having is within a button handler I run a loop to load config data from a file to the GUI before allowing it to be edited. This takes around 2-3 seconds to complete. While this blocking in the event handler is happening, my higher priority communication thread is being blocked. There are no locks are thread syncs in place. The communicatio thread has no dependencies on the GUI thread.
This is how I spawn my comm thread:
MbWorkerThread = new Thread(MbPollingThread);
MbWorkerThread.IsBackground = true;
MbWorkerThread.Priority = ThreadPriority.AboveNormal;
MbWorkerThread.Start();
It is an MTA application. Also, I have tried to use Thread.Sleep(1) in the GUI event handler to yield to the higher priority thread and it does not work. I also tried using signals to yield to the higher priority thread, and that does not work. The only thing that works is if I place Application.DoEvents() in the loop while loading config in the event handler. This of coarse whas just a test, as I do not want to sprinkle Application.DoEvents() throught my code to make it work since I know Application.DoEvents() is dangerous.
My understanding is that the primary GUI thread is a foreground thread, but a thread none the less. Also, I have made the communication thread a background thread just to allow it to be killed when the primary thread is exited.
I have tried everything, I have search the Internet endlessly before asking this question.
Any help will be greatly appreciated.
P.S. - I though about a form timer but I know it runs in the GUI thread so that would not help. I though about another thread but I really did not what to marshall GUI updates via Invoke.
Your program starts in Main(), where you typically call Application.Run( new MyForm() ). Application.Run() implements the standard Windows Message Pump, which deals with messages from the OS and other applications, including user input, inter-process communication, repaint requests, etc.
GUI events, like Button click, are dispatched via this thread. If you perform long-running work in an event handler, other messages are not being processed.
Application.DoEvents() blocks the calling thread, and waits for all pending messages to be processed. If DoEvents helps your communication thread when Sleep(1) did not, then I suspect there is a dependency between your communication thread and the GUI/Message Pump thread.
Even if this is not the case, it is not a good idea to block the GUI thread. Move your file loading into the background with ThreadPool.QueueUserWorkItem() and marshal the results back to the UI at the end with Invoke or BeginInvoke.
BeginInvoke instead of Invoke fixed the issue. Thanks for the replies.
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 am aborting a thread (will be threads soon enough) and the problem is i need to stall until all threads have been aborted.
After doing the Thread.Abort(); I thought of using the Thread.Join() to wait until its been fully aborted. However that doesnt work. It just waits forever. How can i abort each thread and wait until its done before continuing?
Additional information: If your curious why - in this case I am closing a window, I pass a delegate func into the thread which it calls when its done (or aborted). If I dont stall then the window will close and the function will call invalid handles/objs. I can easily use the same method, stick a flag in and loop & sleep until all flags are set but that doesnt feel right.
I've learnt from many years experience with threads that there are a couple of rules that, if followed, make life a lot easier.
The one pertinent to this question is:
let threads control their own resources, including their lifetime.
I wouldn't abort a thread, I'd simply set up a communications method between the threads creator and the thread itself to signal the thread to terminate, and then let the thread itself shut down.
This method can often be as simple as a write-by-creator/read-by-thread flag which controls the threads main loop. If the thread has long running tasks while in the loop, you should also check periodically.
Then the creator thread should just join until the thread exits. Properly designed, you can set an upper limit to the time this will take.
Use a synchronisation object such as an Event. For example, each background thread has an Event associated with it. When the thread is terminating, it signals the Event. The main thread does a WaitHandle.WaitAll on the set of Events, and proceeds only when all Events are signalled.
Be warned that if there is a chance that the background threads will take a long time to terminate, blocking the main thread while waiting for them would create a bad user experience. So if this is the case, you may want to hide the window before blocking. Also, you'll want to test what the impact of this is on your callback delegate -- if the UI thread is blocked in a wait, will it be able to handle your delegate?
Might not a better design be not to call the delegate if the thread is being killed due to the window closing? Just have the main thread tell the background threads why they are terminating and have them skip the callback if the reason is "window closing." (This assumes that you are communicating with the threads, as Pax rightly recommends, rather than just calling Abort.)