本文参考自:http://stackoverflow.com/questions/9586006/application-current-dispatcher-begininvoke-where-to-place-try-catch
我在项目中,写了一个http异步请求,然后在callback中写了,Dispatcher.BeginInvoke(()={//前台展示});
因为异步可能没执行完,然后就直接引用了,然后报错,错误:“System.Reflection.TargetInvocationException”类型的未经处理的异常在 System.Windows.ni.dll 中发生。这种情况一般是因为begininvoke 造成的,begininvoke往系统编译好的clr进行Reflection(概念不是很懂,字面意思是反射,就是从系统的“运行时”调用)的时候报的错,不能像一般的程序方法一样的外包 try catch ,必须在里面try catch
想抓住异常,参考了stackoverflow中介绍的方法,据介绍:“BeginInvoke will Execute your Method in anoster Stack. So a try-catch around "Application.Current.Dispatcher.BeginInvoke" will not work.”就是说,begininvoke执行的方法在别的堆栈里,所以外面的trycatch不工作。
方法一(错误):
try { Dispatcher.BeginInvoke(() => { //赋值给前台控件,这种方法抓不住异常 }); } catch (Exception ex) { MessageBox.Show(ex.Message); }
方法二(正确):
Dispatcher.BeginInvoke(() => { try { //赋值给前台控件,这种方法可以抓住异常 } catch (Exception ex) { MessageBox.Show(ex.Message); } });