Por que Dispatcher.BeginInvoke desembrulha TargetInvocationException para ThreadStart, mas não para Action?
Considere os dois aplicativos a seguir:
1:public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.Exception.GetType());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Dispatcher.BeginInvoke((ThreadStart)delegate
{
throw new AccessViolationException("test");
}, DispatcherPriority.Input);
}
}
2:public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.Exception.GetType());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke((Action)delegate
{
throw new AccessViolationException("test");
}, DispatcherPriority.Input);
}
}
Ambos os aplicativos são idênticos, exceto pelo uso de dois tipos diferentes de delegados,Action
eThreadStart
(que possuem a mesma assinatura).
Resultados (janela de saída, quando você chama o manipulador de eventos usando um clique no botão)
1: System.Reflection.TargetInvocationException2: System.AccessViolationExceptionPor que os aplicativos diferem no comportamento?
Pilha completa para a exceção 1:
System.Reflection.TargetInvocationException: Ein Aufrufziel hat einen Ausnahmefehler verursacht. ---> System.AccessViolationException: test
bei ExceptionTest.MainWindow.<Button_Click>b__0() in c:\Users\fschmitz\Documents\Visual Studio 11\Projects\ExceptionTest\MainWindow.xaml.cs:Zeile 40.
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
bei System.Delegate.DynamicInvokeImpl(Object[] args)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)