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