简体   繁体   English

在WPF中处理C ++ dll中未处理的异常

[英]Handle unhandled exception from c++ dll in WPF

My WPF app uses external DLL's method (c++, nothing with UI, just logic) like this: 我的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;
}

Note, that SomeWPFMethod called in separate from UI thread (if this matter). 请注意,SomeWPFMethod与UI线程分开调用(如果有此问题)。

When there is something wrong inside dll I've got 当dll中出现问题时,我得到了

An unhandled exception of type 'System.AccessViolationException' occurred 发生类型为'System.AccessViolationException'的未处理异常

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. 如果extern方法失败,我什么也不想做,但是应用程序仍然可以工作。 Now it's crashed. 现在它崩溃了。

Since SomeWPFMethod is called in a thread separate from the UI thread, 由于SomeWPFMethod是在与UI线程分开的线程中调用的,

Application.Current.DispatcherUnhandledException 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. 将无法捕获此异常,因为它仅从WPF创建的主UI线程捕获未处理的异常。

Seems you need to use 似乎您需要使用

AppDomain.CurrentDomain.UnhandledException 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 - 您可以参考以下文章,它们涵盖了在WPF中深入处理未处理异常的正确方法-

https://dzone.com/articles/order-chaos-handling-unhandled https://dzone.com/articles/order-chaos-handling-unhandled

https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx https://msdn.microsoft.com/zh-CN/library/system.appdomain.unhandledexception.aspx

Hope this solves your problem. 希望这能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM