There is one cunning and a very robust mechanism using the idea of see seeding of the exception.
It was invented by one former Microsoft engineer and was is implemented in .NET without much buzz about it. I used to fully implement it. It uses fully documented Windows API, but the non-portable part of it — you need to modify Instruction Pointer in thread's swapped out status data.
I tried to explain how it works in my comments on this page:
How do I abort a specific thread that is already running?[
^]. To locate it, please find the Answer by Olivier and my comments by the key words "exception seeding".
The key API to use is
GetThreadContext
(
http://msdn.microsoft.com/en-us/library/ms679362(v=vs.85).aspx[
^]) and
SetThreadContext
(
http://msdn.microsoft.com/en-us/library/ms680632(v=vs.85).aspx[
^]). What's important, you can call it from the thread other then the one to be aborted. You suspend the thread, get its content, modify Instruction Pointer to point to your function throwing the exception (define exception class, say "
ThreadAbortException
") and resume the thread. When you resume the thread, stack frame will be broken, but it does not matter, because you jump to exception throwing method (will never return). The thread body should run in the try-catch block, catch
ThreadAbortException
and perform all post mortal clean-up there. Most importantly, release all locks, etc.
To see what can you avoid by replacing
TerminateThread
with this mechanism, read help on this topic:
http://msdn.microsoft.com/en-us/library/ms686717(v=vs.85).aspx[
^]. You can avoid all problems (and many less difficult ones) by handling
ThreadAbortException
.
The implementation is not very difficult at all. It replaces unsafe
TerminateThread
with a very gentle way to abort it, leaving a thread with a possibility to process its post-mortal action accurately. You can even avoid termination of the thread by getting it all in a loop.
The implementation is fairly simple and the code is short, the mechanism is very robust.
Please ask your questions if you're interested, I'll be able to help you, but you better try to implement it yourself.
[EDIT]
See also my recent answer:
Problem with creating Process from dedicated thread[
^].
—SA