Let's say i have .NET Core 2.0/2.1 program. There is a thread executing the following method. I want to stop it forcefully.
Important notes:
Cooperative multitasking (for example, with CancellationToken) is a good thing, but not the case
XY problem (https://en.wikipedia.org/wiki/XY_problem) does exist, but i just want to know if stopping this thread is actually possible
while (true)
{
var i = 0;
try
{
Console.WriteLine($"Still alive {i++}");
}
catch (Exception e)
{
Console.WriteLine($"Caught {e.GetType().Name}");
}
}
Tried several options:
- Thread.Abort - throws PlatformNotSupportedException, not an option
- Thread.Interrupt - only works for threads in WaitSleepJoin state, which is not the case
- Calling native API methods such as TerminateThread from kernel32.dll on Windows. This approach has a lot of problems like non-released locks (https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx)
Concerns, from most important to least:
- Releasing locks
- Disposing objects in using directives
- Actually collecting allocated objects
(as a corner case we can assume that out thread does not perform any heap allocations at all)