[英]Handle unhandled exception from c++ dll in WPF
我的WPF应用程序使用外部DLL的方法(c ++,UI不包含任何内容,仅包含逻辑),如下所示:
[DllImport("myExternDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern int externalMethod(string str);
int SomeWPFMethod()
{
int res;
try
{
res = externalMethod(str);
}
catch(Exception e)
{
LogError(e)
return -1;
}
return res;
}
请注意,SomeWPFMethod与UI线程分开调用(如果有此问题)。
当dll中出现问题时,我得到了
发生类型为'System.AccessViolationException'的未处理异常
例外。
为应用程序设置了一个未处理的异常方法,但这无济于事:
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
e.Handled = false;
return;
}
ShowUnhandledException(e);
}
是否有可能以某种方式处理异常以防止应用程序崩溃?
如果extern方法失败,我什么也不想做,但是应用程序仍然可以工作。 现在它崩溃了。
由于SomeWPFMethod是在与UI线程分开的线程中调用的,
Application.Current.DispatcherUnhandledException
将无法捕获此异常,因为它仅从WPF创建的主UI线程捕获未处理的异常。
似乎您需要使用
AppDomain.CurrentDomain.UnhandledException
它捕获在特定应用程序域的上下文下运行的所有线程生成的未处理异常。
您可以参考以下文章,它们涵盖了在WPF中深入处理未处理异常的正确方法-
https://dzone.com/articles/order-chaos-handling-unhandled
https://msdn.microsoft.com/zh-CN/library/system.appdomain.unhandledexception.aspx
希望这能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.