Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top