Why does Dispatcher.BeginInvoke unwrap TargetInvocationException for ThreadStart but not for Action?

前端 未结 1 548
轻奢々
轻奢々 2021-01-13 16:39

Consider the following two applications:

1:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();         


        
相关标签:
1条回答
  • 2021-01-13 17:29

    I think the culprit lies within InternalRealCall method of ExceptionWrapper. More specifically the following part where we have Action delegates special cased.

    Action action = callback as Action;
    if (action != null)
    {
        action();
    }
    else
    {
        // ... removed code ..
        obj = callback.DynamicInvoke();
    }
    

    Since Action delegates are called directly the resulting exception is the one you originally thrown. For all other delegate types, since the invocation goes through reflection the exception is wrapped in a TargetInvocationException.

    In conclusion, the differences is a side-effect related to how the provided delegate is called, directly or through reflection.

    0 讨论(0)
提交回复
热议问题