title: FatalExecutionEngineError detected in C# code after calling TerminateThread in C++ code
body: <p>If I call TerminateThread from C++ code, then later I'm getting FatalExecutionEngineError MDA later. That error mostly occurs when I'm doing different operations on strings (i.e. concat). Code listed below is just shows how to reproduce it.</p>
  
  <p>Why it happens? How can I fix it and still use TerminateThread?</p>
  
  <p>Thanks</p>
  
  <p>Error is:<br></p>
  
  <pre><code>FatalExecutionEngineError was detected
  Message: The runtime has encountered a fatal error. 
  The address of the error was at 0x7880bb35, on thread 0x18f0. 
  The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. 
  Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
  </code></pre>
  
  <p>C++ code:<br>
  Module.cpp:<br></p>
  
  <pre><code>#include "ThreadModule.h"
  using namespace ThreadModule;
  
  DWORD WINAPI workThread(LPVOID lpParam) {
      while(1) {
          System::Threading::Thread::Sleep(5);
          printf(".");
      }
      return 0;
  }
  
  bool Module::StartThread() {
      handle = CreateThread(
          NULL,
          0,
          workThread,
          NULL,
          0,
          &amp;threadIdInput);
      return true;    
  }
  
  bool Module::StopThread() {
      TerminateThread(handle, 0);
      handle = NULL;
      return true;
  }
  </code></pre>
  
  <p>C# code:<br></p>
  
  <pre><code>static void Main(string[] args)
  {
      Module module = new Module();
  
      module.StartThread();
      string s = "";
      for (int i = 0; i &lt; 10000; i++)
      {
          s += i.ToString();
      }
      module.StopThread();
      s = "";
      for (int i = 0; i &lt; 10000; i++)
      {
          s += i.ToString();  //After ~250 iteration get exception
      }
      Console.WriteLine("Completed!!");
  }
  </code></pre>