我遇到了一个非常不寻常的问题,如果客户端计算机上缺少 DLL,应用程序将卡住并显示标准“应用程序没有响应”。但是,据我所知问题是什么,我想找到一种方法来捕获此异常(缺少 DLL)并在对话框中显示消息,显示有意义的信息以帮助识别缺少哪个 DLL。这将使应用程序能够更优雅地死亡。
在客户端计算机上调试时,我收到错误:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: Could not load file or assembly 'Some.DLL' or one of its dependencies. The system cannot find the file specified.
但是,在发布中,应用程序崩溃并且没有响应。
查看documentation对于此错误,XamlParseException
通常发生在 InitializeComponent();
方法内:
For pages of an application, when the XamlParseException is thrown, it is usually in the context of the InitializeComponent call made by your page class, which is the entry point for the WPF application model's usage of the WPF XAML parser at the per-page level. Therefore another possible handling strategy is to place try/catch blocks in InitializeComponent. However, this technique does not integrate well with templates, visual design surfaces and other generated sources that hook up InitializeComponent.
所以,我可以做这样的事情:
public MyView()
{
try
{
InitializeComponent();
}
catch (XamlParseException ex)
{
//Do something useful with the error.
}
}
这当然是可能的,但是它需要在几乎所有控件中使用此代码,这显然是荒谬的。更不用说它并没有真正解决DLL丢失的问题。
所以,我的问题是:
- 是否可以捕获丢失的 DLL 并显示包含该 DLL 名称的消息?
- 是否有更优雅的方式来捕获
XamlParseException
?
谢谢。
最佳答案
是的,这当然是可能的。
为此,您需要覆盖应用程序首次启动时发生的情况。
打开 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:无法加载文件或程序集“{此处缺少 DLL 名称}”或其依赖项之一。该系统找不到指定的文件。在 {Project}.{抛出错误的地方}
关于c# - 捕获 XamlParseException 中丢失的 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519813/