我的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' 发生
异常。
为app设置了unhanded exception方法,但这没有做任何事情:
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方法失败,我不想做任何事情,但app应该仍然有效。现在它崩溃了。
答案 0 :(得分:1)
由于SomeWPFMethod是在与UI线程分开的线程中调用的,
Application.Current.DispatcherUnhandledException
将无法捕获此异常,因为它仅从WPF创建的主UI线程捕获未处理的异常。
似乎你需要使用
AppDomain.CurrentDomain.UnhandledException
它捕获在特定应用程序域的上下文中运行的所有线程生成的未处理异常。
您可以参考以下文章,其中介绍了在WPF中深入处理未处理异常的正确方法 -
https://dzone.com/articles/order-chaos-handling-unhandled
https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
希望这能解决你的问题。