1

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.

Ateeq
  • 797
  • 2
  • 9
  • 27
  • 1
    Are you trying to abort a thread running in another process? – Gusdor Feb 03 '15 at 09:41
  • 7
    Your question sounds like *how to shoot on my foot ?* Can you explain what you're trying to do instead? Why do you need to terminate a thread? – Sriram Sakthivel Feb 03 '15 at 09:42
  • You've got a answer using `TerminateThread` [below](http://stackoverflow.com/a/28295713/2530848) . You can use it if you really know what it is doing and what are the consequences. It is unlikely you could know about the consequences of `TerminateThread` when you're not aware of existence of such function. – Sriram Sakthivel Feb 03 '15 at 10:01
  • @Gusdor that is how it read for me too... – Meirion Hughes Feb 03 '15 at 10:53

1 Answers1

3

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);
Community
  • 1
  • 1
aevitas
  • 3,753
  • 2
  • 28
  • 39