I'm using a thread in C# where I've set the IsBackground property to true. The thread is running some code in a loop until the application closes. When the application is closed the thread also stops executing (because I've set IsBackground = true).
How does the application kill the thread? It seems that it doesn't do it by calling abort because I don't get a ThreadAbortException. Does it happen behind the scenes? I'd like to do some rollback in my finally block of the loop.
I know I could just call abort on the thread myself, but I want to know how the application closes my background thread and if I can react on it from inside the thread. I know I can subscribe to the Application.ApplicationExit event, but I'm running this code in both a service and a winform and I'd prefer catching an exception inside the loop so I'm able to rollback in the finally statement.
Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. You should run any blocking operations on a separate thread within the service to avoid Application Not Responding (ANR) errors.
Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.
It seems that it doesn't do it by calling abort because I don't get a ThreadAbortException
It does, the CLR has two ways to abort a thread. The "normal" way, invoked through Thread.Abort(), the thread can see a ThreadAbortException. But there's also a rude abort, works the same way. But minus the TAE and no finally blocks execute. You can't observe it.
The Started thread
enters the Running state (i.e., begins executing) when the operating system assigns a processor to the thread
. When a Started thread receives a processor for the first time and becomes a Running thread, the thread executes its ThreadStart delegate
, which specifies the actions the thread will perform during its lifecyle. When a program creates a new Thread, the program specifies the Thread's ThreadStart delegate
as the argument to the Thread constructor.
A Running thread enters the Stopped (or Dead)
state when its ThreadStart delegate
terminates. In your case your main thread is terminates. So, your ThreadStart delegate
object does not remains in memory. When there are no references to the thread object, the garbage collector can remove the thread object from memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With