Skip to content

Instantly share code, notes, and snippets.

@lydonchandra
Forked from fresky/KillThread.cs
Created November 26, 2015 02:59
Show Gist options
  • Save lydonchandra/ac9f8c08b6d3a9e80e7a to your computer and use it in GitHub Desktop.
Save lydonchandra/ac9f8c08b6d3a9e80e7a to your computer and use it in GitHub Desktop.
Kill thread in C#
class Program
{
static int threadID=0;
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern bool TerminateThread(IntPtr hThread, uint dwExitCode);
static void Main(string[] args)
{
Console.Out.WriteLine("Forking off threads...");
for(int i=0; i<5; i++)
{
Thread t = new Thread(RunInfinite);
t.Start();
Console.Out.WriteLine("Thread " + t.Name + "(ManagedThreadId: "+t.ManagedThreadId+") created!");
}
ProcessThreadCollection processThreads = Process.GetCurrentProcess().Threads;
Console.Out.WriteLine("=> Total threads: " + processThreads.Count);
foreach (ProcessThread pt in processThreads)
{
int timerSeconds = 2;
while (timerSeconds-- > 0)
{
Console.Out.Write("
Seconds before thread "+pt.Id+" dies: " + timerSeconds);
System.Threading.Thread.Sleep(1000);
}
IntPtr ptrThread = OpenThread(1, false, (uint)pt.Id);
if (AppDomain.GetCurrentThreadId() != pt.Id)
{
try
{
TerminateThread(ptrThread, 1);
Console.Out.Write(". Thread killed.
");
}
catch(Exception e)
{
Console.Out.WriteLine(e.ToString());
}
}
else
Console.Out.Write(". Not killing... It's the current thread!
");
}
Console.Out.WriteLine("=> Total threads now: " + Process.GetCurrentProcess().Threads.Count);
Console.ReadLine();
}
public static void RunInfinite()
{
while (true)
{
System.Threading.Thread.Sleep(10000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment