【问题标题】:Catching missing DLL in XamlParseException在 XamlParseException 中捕获丢失的 DLL
【发布时间】:2015-09-11 09:13:36
【问题描述】:

我有一个非常不寻常的问题,如果客户端计算机上缺少 DLL,应用程序将冻结并显示标准 “应用程序没有响应”。但是,我知道问题出在哪里,我想找到一种方法来捕获此异常(缺少 DLL)并在显示有意义信息的对话框中显示消息,以帮助确定缺少哪个 DLL。这将允许应用程序有一个更优雅的死亡。

在客户端计算机上调试时,我收到错误:

在 PresentationFramework.dll 中发生了“System.Windows.Markup.XamlParseException”类型的第一次机会异常

附加信息:无法加载文件或程序集“Some.DLL”或其依赖项之一。系统找不到指定的文件。

然而,在 release 中,应用程序崩溃并且没有响应。

查看documentation这个错误,XamlParseException通常出现在InitializeComponent();方法内部:

对于应用程序的页面,当 XamlParseException 被抛出时,通常是在您的页面类进行的 InitializeComponent 调用的上下文中,这是 WPF 应用程序模型在每次使用 WPF XAML 解析器的入口点-页面级别。 因此另一种可能的处理策略是在 InitializeComponent 中放置 try/catch 块。但是,这种技术不能很好地与模板、可视化设计图面和其他连接 InitializeComponent 的生成源集成。

所以,我可以这样做:

public MyView()
{
    try
    {  
        InitializeComponent();
    }
    catch (XamlParseException ex)
    { 
        //Do something useful with the error.
    }
}

这当然是可能的,但是它需要在几乎所有控件中使用此代码,这显然是荒谬的。更何况它并不能真正解决缺少 DLL 的问题。

所以,我的问题是:

  • 是否可以捕获丢失的 DLL 并显示包含该 DLL 名称的消息?
  • 有没有更优雅的方式来捕捉XamlParseException

谢谢。

【问题讨论】:

    标签: c# wpf xaml dll


    【解决方案1】:

    是的,这当然是可能的。

    为此,您需要覆盖应用程序首次启动时发生的情况。

    打开您的Application.xaml.vb,并添加以下代码:

        protected override void OnStartup(StartupEventArgs e)
        {
            // add an event handler for the UnhandledException event
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(HandleException);
            // start up the application
            base.OnStartup(e);
        }
        // what to do when the exception is thrown
        void HandleException(object sender, UnhandledExceptionEventArgs e)
        {
            // do something with the exception
            MessageBox.Show(e.ExceptionObject.ToString());
        }
    

    e.ExceptionObject.ToString() 的输出包含问题。在您描述的情况下,可能会有嵌套异常,内部异常声明:System.IO.FileNotFoundException: Could not load file or assembly '{missing DLL name here}' or one of its dependencies. The system cannot find the file specified. at {Project}.{where the error was thrown}

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 2020-04-20
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      相关资源
      最近更新 更多