0

I created a Thread, and want to kill him. I found my Thread in Process.GetCurrentProcess().Threads, but it has ProcessThread class, and can't be cast to Thread, so i can't kill him.

foreach (Thread thread in currentProcess.Threads)//throw error:unable to cast
{
       if (thread.ManagedThreadId.Equals(processThreadId))
       {

            thread.Abort();
       }
}
Frontear
  • 1,150
  • 12
  • 25
  • How did you create it? Don't you have a `Process` reference to which you can [send a SIGKILL](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.kill?view=netframework-4.8) or something like that? – Fildor Dec 02 '19 at 15:36
  • 1
    If you started the thread, wouldnt you keep that thread detail around until its done? then you could cancel the thread.. – BugFinder Dec 02 '19 at 15:40
  • 4
    Before you continue, you need to know why you want to kill the thread. Aborting threads should be avoided at all times. It would imply some bad code design _(maybe because a thirdparty library created a non-stoppable thread)_. It would be better to terminate the thread the normal way instead of aborting it. If your program hangs because a thread is hanging, you could set the [IsBackground](https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isbackground?view=netframework-4.8) property of the thread by default on true, so I won't blocks the termination of your application. – Jeroen van Langen Dec 02 '19 at 15:43

1 Answers1

0

System.Diagnostics.ProcessThread isn't the same notion than System.Threading.Thread.

A quick solution is to save all task created in ConcurrentBag

int processThreadId = 0;

        var threads = new ConcurrentDictionary<int,Thread>();
        ///...Some action

        var newThread = new Thread(()=> {});
        newThread.Start();
        threads.TryAdd(newThread.ManagedThreadId,newThread); 

        ///...Some action
        Thread thread = null;       
        if(threads.TryRemove(processThreadId,out thread)){
            thread.Abort();
        }

It seems possible to translate ManagedThreadId into NativeThreadId for more information Getting the thread ID from a thread

Tohm
  • 305
  • 1
  • 5