Question Terminating a Thread

Drache

Active member
Joined
Apr 8, 2006
Messages
26
Programming Experience
Beginner
Can anyone tell me how to kill a thread immediately.
I have tried MyThread.Abort, but it seems to do nothing. Someone told me it's because 'Abort' waits for the current operation to complete, but my thread will run for over 30 minutes before that happens.

Any help would be appreciated.
 
Abort is a 'request' that causes the thread to immediately throw a ThreadAbortException, except in one case where thread is current waiting for an unmanaged call to complete, further it may be delayed by the thread executing in a Try block for the Finally code block to complete. If your thread isn't aborted I guess this means it is somewhere down the line calling unmanaged code. I can think of one way around this, and that is creating a new AppDomain, that creates a background thread to do the work. Now if you unload that AppDomain the background thread is immediately terminated regardless of state (equivalent of closing/killing an app). How wise this is in regard to the state of the unmanaged object I can't say, there is always a chance doing this may leave the unmanaged object in a corrupt state.
 
Terminating a Thread - AppDomain

I have never used AppDomain's so you will have to excuse me if I have made a mistake, but I have just looked at MSDN and it shows the following regarding unloading an AppDomain.

Unload
Performs a graceful shutdown of the domain. The application domain is not unloaded until all threads running in the domain have either stopped or are no longer in the domain.

Can you explain how I would go about stopping the thread in the domain, is it different from MyThread.Abort

Thank you.
 
Yes, but a background thread is stopped when appdomain is unloaded even if it busy, while a foreground thread will prevent the appdomain to be unloaded until it is finished. See Thread.IsBackground Property (System.Threading)
I may of course be wrong, as I said this was just an idea from top of my head, but AppDomain is the top object of the .Net process and that's how background/foreground threads work when the regular application (domain) is closed, background threads are just stopped.
You should just give it a try if you find this interesting, I might even do that myself later (if I could find some unmanaged call that stalls). :)
I did read the Unload help now, and it says "The threads in domain are terminated using the Abort method", so perhaps this is also the case for background threads?
 
Terminating a Thread - AppDomain Solved

Thank you for all your help.


I am not sure how to mark a thread as solved, but nevertheless thank you.
 
Back
Top