【问题标题】:Handle unhandled exception from c++ dll in WPF在 WPF 中处理来自 c++ dll 的未处理异常
【发布时间】:2017-04-22 15:12:26
【问题描述】:

我的 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);
        }

是否有可能以某种方式处理异常以防止应用程序崩溃?

如果外部方法失败,我不想做任何事情,但应用程序应该仍然可以工作。现在它崩溃了。

【问题讨论】:

标签: c# c++ wpf dll


【解决方案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

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 2011-09-01
    • 1970-01-01
    • 2015-05-19
    • 2011-02-20
    • 2020-04-07
    • 2012-12-03
    • 2012-05-05
    相关资源
    最近更新 更多