如果我从 C++ 代码调用 TerminateThread,那么稍后我会得到 FatalExecutionEngineError MDA。该错误主要发生在我对字符串(即 concat)执行不同操作时。下面列出的代码只是显示如何重现它。
为什么会发生?如何修复它并仍然使用 TerminateThread?
谢谢
错误是:
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.
C++ 代码:
Module.cpp:
#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,
&threadIdInput);
return true;
}
bool Module::StopThread() {
TerminateThread(handle, 0);
handle = NULL;
return true;
}
C#代码:
static void Main(string[] args)
{
Module module = new Module();
module.StartThread();
string s = "";
for (int i = 0; i < 10000; i++)
{
s += i.ToString();
}
module.StopThread();
s = "";
for (int i = 0; i < 10000; i++)
{
s += i.ToString(); //After ~250 iteration get exception
}
Console.WriteLine("Completed!!");
}