How can I safely kill a thread from a ThreadPool
That is, how can I kill/abort the thread resulting from queueing like this:
ThreadPool.QueueUserWorkItem( new WaitCallback(someMethod), someObject);
The problem is as follows:
1. Once in a while (much more often than we can afford for the critical production application!..) the Image.SelectActiveFrame(...) method hangs, consumes 98 to 99 % of CPU, and we have to reboot the server... The only possibility I see is that it happens when the data returned by a remote server and being processed by the SelectActiveFrame method is somehow corrupted.
2. This method is called inside another method which runs on a separate thread from a ThreadPool.
3. I can't rewrite the code so that to use Thread class instead of the queueing the method in a pool, because this method's dll is tightly coupled with several other applications which cannot be refactored at this time. So, the only way to solve the problem as I see it is to kill the thread...
Could someone help, please Is there a better solution If not, how can I safely kill a thread from a ThreadPool
Thank you very much.

Killing a ThreadPool thread
grcor
Laura Bagnall
The other posters were accurate when they discouraged aborting an active thread.
The thread can be performing any number of activities - including marshalling into native code, operating on a string/lock, etc..
Once you have aborted the thread, it is recommended that you do quick and scoped cleanup, then tear down the AppDomain ~ since the state of the AppDomain (strings, locks, etc.) may be undefined.
Callstacks for the hangs with SelectActiveFrame when hanging would be useful.
Thanks!
Stephen
MauiSon
I think his point is a BCL function is hanging. You can't inject use of an event or wait handle into framework code.
drtom
A more elegant solution would be to use AutoResetEvent. This would allow you to wait for any number of signals (including a timeout) and then either carry out the abort or normal processing.
For what it's worth, calling Abort on a thread should be a last resort and you could again use something like ManualResetEvent to signal when a thread needs to terminate, rather than the drastic termination of Thread.Abort.
Hope this information was of some use to you.
Melissa_Janet
I think I've just found a workaround:
1. Run returnedImage.SelectActiveFrame method in a separate "regular" thread (like: Thread t = new Thread(new ThreadStart(ThreadProc));
2. Use a timer to watch for the method (containing the returnedImage.SelectActiveFrame method call) completion.
3. If it's not done in due time, --> t.Abort(); t.Join();
I still need to test if it's gonna work when the CPU consumption is 99%...