I need to terminate a specific Thread that I already know the Id of it, I get the ID by getting the
System.Diagnostics.ProcessThread
and I already detect the thread ID that I need to terminate
what can I do to terminate it.
You can do this using a couple P/Invoke methods. First off, call OpenThread
on the thread with the ID you found to obtain a handle to it:
IntPtr handle = OpenThread(THREADACCESS_SUSPEND_RESUME, false, (uint)thd.Id);
Then call SuspendThread
using the handle you just obtained:
if (handle != IntPtr.Zero)
var suspended = SuspendThread(threadHandle) == -1
That suspends the thread - ie. it will no longer be running. If you desperately want to kill it forcefully, you can call TerminateThread
on the handle:
TerminateThread(handle, 0); // Or any other exit code.
Make sure to close the handle after you're done with it, for example inside a finally
block if you're wrapping it in a try/catch.
As mentioned in the comments, terminating a thread forcefully like this is usually not what you want to do - be very careful when using this. Suspending a thread allows you to resume it at a later point, Terminating kills the thread immediately (read more about why you shouldn't abort threads here)
Furthermore, the MSDN documentation on TerminateThread mentions the following:
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.
P/invokes:
[DllImport("kernel32.dll",SetLastError=true)]
static extern int SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle,
uint dwThreadId);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
static extern bool TerminateThread(IntPtr hThread, uint dwExitCode);