Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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