Don't do this! Seriously!
The function that you need to call to kill a thread is the TerminateThread
function, which you can call via P/Invoke. All the reasons as to why you shouldn't use this method are right there in the documentation
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you
know exactly what the target thread is doing, and you control all of
the code that the target thread could possibly be running at the time
of the termination. For example, TerminateThread can result in the
following problems:
- If the target thread owns a critical section, the critical section will not be released.
- If the target thread is allocating memory from the heap, the heap lock will not be released.
- If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be
inconsistent.
- If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other
users of the DLL.
The important thing to note is the bit in bold, and the fact that under the CLR / .Net framework you are never in the situation where you know exactly what the target thread is doing (unless you happen to write the CLR).
To clarify, calling TerminateThread on a thread running .Net code could quite possibly deadlock your process or otherwise leave in a completely unrecoverable state.
If you can't find some way to abort the connection then you are far better off just leaving that thread running in the background than trying to kill it with TerminateThread
. Other people have already posted alternative suggestions on how to achieve this.
The Thread.Abort
method is slightly safer in that it raises a ThreadAbortException
rather than immediately tearing down your thread, however this has the disadvantage of not always working - the CLR can only throw the exception if the CLR is actually running code on that thread, however in this case the thread is probably sat waiting for some IO request to complete in native SQL Server Client code instead, which is why your call to Thread.Abort
isn't doing anything, and won't do anything until control is returned to the CLR.
Thread.Abort
also has its own problems anyway and is generally considered a bad thing to be doing, however it probably wont completely hose your process (although it still might, depending on what the code running is doing).
TerminateThread
– ViolateTerminateThread
? – ViolateTerminateThread
"is a dangerous function", its right there in the documentation you linked. – Juanjuana