3

In my ASP.NET Core 2.2 App I call a native function via PInvoke. Under some conditions the function results in an endless loop. I do not have access to the source of the lib.

This is how I execute the function in a separate thread:

var thread = new Thread(
    () =>
    {
         threadId = GetCurrentThreadId();
         try
         {
              result = callFunctionWithPinvoke();
         }
         catch (Exception ex)
         {
              threadEx = ex;
         }
    })
    {
        Name = "Calculation",
        Priority = ThreadPriority.Highest
    };

thread.Start();

After some timeout I try to stop the thread like this:

thread.Interrupt();
thread.Abort();

if (thread.IsAlive)
{
     var success = TerminateThread(new IntPtr(threadId), 1);
     var lastError = GetLastError();
}

Even the very bad TerminateThread function is not able to kill the thread.

My question now is: What do I miss here? Can I kill a thread with an endless loop, or is that simply not possible?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mklieber
  • 192
  • 11
  • 2
    You could be interested by my answer here: https://stackoverflow.com/a/55709530/403671 – Simon Mourier Jan 29 '20 at 10:18
  • Indeed that looks interesting. I´ll give it a try and let you know if that works in my case. – mklieber Jan 29 '20 at 11:32
  • 3
    `TerminateThread` requires a *handle* to the thread, not the thread ID. Both snugly fit in an `IntPtr`, but they're very different things. (Incidentally, I would argue against a design using `TerminateThread` -- either abandon the thread and move on, or if you know this'll burn 100% CPU or suchlike, set up monitoring so the entire app can be torn down and restarted. The problem with thread termination is that the corrupted state this can result in can become impossible to reliably detect, leaving you worse off than with a process restart). – Jeroen Mostert Jan 29 '20 at 12:22

0 Answers0