My WPF app uses external DLL's method (c++, nothing with UI, just logic) like this:
[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;
}
Note, that SomeWPFMethod called in separate from UI thread (if this matter).
When there is something wrong inside dll I've got
An unhandled exception of type 'System.AccessViolationException' occurred
exception.
A have unhanded exception method set for app, but this does nothing:
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);
}
Is there possible somehow to handle the exception to prevent application from crash?
If extern method fails, I don't want to do anything, but app should still work. Now it's crashed.
Since SomeWPFMethod is called in a thread separate from the UI thread,
Application.Current.DispatcherUnhandledException
will not be able to catch this exception since it catches unhandled exceptions only from the main UI thread created by WPF.
Seems you need to use
AppDomain.CurrentDomain.UnhandledException
It catches unhandled exceptions generated from all threads running under the context of a specific application domain.
You can refer to the following articles that cover proper way to handle unhandled exceptions in WPF at great depth -
https://dzone.com/articles/order-chaos-handling-unhandled
https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
Hope this solves your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.