我正在尝试编写一个可以加载托管插件的插件系统。如果有任何例外,主机应该能够卸载插件。 我POC我在C#中抛出这样一个异常的示例代码库...托管clr和捕捉线程异常
public static int StartUp(string arguments)
{
Console.WriteLine("Started exception thrower with args {0}", arguments);
Thread workerThread = new Thread(() =>
{
Console.WriteLine("Starting a thread, doing some important work");
Thread.Sleep(1000);
throw new ApplicationException();
}
);
workerThread.Start();
workerThread.Join();
Console.WriteLine("this should never print");
return 11;
}
然后我有本地的Win32控制台应用程序,这样的..
int _tmain(int argc, _TCHAR* argv[])
{
ICLRMetaHost *pMetaHost = NULL;
HRESULT hr;
ICLRRuntimeInfo *runtimeInfo = NULL;
__try
{
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pMetaHost);
hr = pMetaHost->GetRuntime(L"v4.0.30319",IID_ICLRRuntimeInfo,(LPVOID*)&runtimeInfo);
ICLRRuntimeHost *runtimeHost = NULL;
hr = runtimeInfo->GetInterface(CLSID_CLRRuntimeHost,IID_ICLRRuntimeHost, (LPVOID*)&runtimeHost);
ICLRControl* clrControl = NULL;
hr = runtimeHost->GetCLRControl(&clrControl);
ICLRPolicyManager *clrPolicyManager = NULL;
clrControl->GetCLRManager(IID_ICLRPolicyManager, (LPVOID*)&clrPolicyManager);
clrPolicyManager->SetDefaultAction(OPR_ThreadAbort,eUnloadAppDomain);
hr = runtimeHost->Start();
DWORD returnVal = NULL;
hr = runtimeHost->ExecuteInDefaultAppDomain(L"ExceptionThrower.dll",L"ExceptionThrower.MainExceptionThrower",L"StartUp",L"test",&returnVal);
runtimeHost->Release();
}
__except(1)
{
wprintf(L"\n Error thrown %d",e);
}
return 0;
}
问题是,如果我使用上面的代码,主机将完成运行托管代码(“永不打印”这行将最终打印) 如果我删除了clrPolicyManager-> SetUnhandledExceptionPolicy(eHostDeterminedPolicy),则主机进程将崩溃。
任何事情都可以在非托管主机上完成,它可以从运行时中正常删除错误的应用程序,并继续工作?
您的代码启用了.NET 1.x异常处理策略。这只是终止线程。不是你想要的,你还需要调用ICLRPolicyManager :: SetDefaultAction()来告诉它在线程中止时卸载应用程序域。你仍然有一个死线程,使用__try/__ catch来捕捉异常。 –
我添加了以下行clrPolicyManager-> SetDefaultAction(OPR_ThreadAbort,eUnloadAppDomain);到代码,我已经更新了代码,但效果是一样的,主机进程仍然崩溃 –
您可能错过了评论的“死线程”部分。你必须抓住SEH异常。异常代码是0xe0434f4d。 http://msdn.microsoft.com/en-us/library/s58ftw19%28v=VS.100%29.aspx –