Killing/aborting 在 c# 中使用它的 ID 的特定线程

Killing/aborting a specific thread using it's ID in c#

我需要终止一个我已经知道它的 Id 的特定线程,我通过获取 System.Diagnostics.ProcessThread 并且我已经检测到需要终止的线程 ID 我该怎么做才能终止它。

您可以使用几种 P/Invoke 方法来完成此操作。首先,使用您找到的 ID 在线程上调用 OpenThread 以获取它的句柄:

IntPtr handle = OpenThread(THREADACCESS_SUSPEND_RESUME, false, (uint)thd.Id);

然后使用刚刚获得的句柄调用SuspendThread

if (handle != IntPtr.Zero)
    var suspended = SuspendThread(threadHandle) == -1

暂停线程 - 即。它将不再是 运行。如果你拼命想强行杀掉,可以在句柄上调用TerminateThread

TerminateThread(handle, 0); // Or any other exit code.

确保在完成处理后关闭句柄,例如在 finally 块中,如果您将其包装在 try/catch 中。

如评论中所述,像这样强行终止线程通常不是您想要做的 - 使用时要非常小心。 暂停 线程允许您稍后恢复它,终止 会立即终止线程(阅读更多内容 about why you shouldn't abort threads here

此外,MSDN documentation on TerminateThread 提到了以下内容:

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);