What's the difference between InvokeAsync and BeginInvoke for WPF Dispatcher

前端 未结 4 866
庸人自扰
庸人自扰 2020-12-08 13:09

I noticed in .NET 4.5 that the WPF Dispatcher had gotten a new set of methods to execute stuff on the Dispatcher\'s thread called InvokeAsync. Before, .NET 4.5 we had Invoke

4条回答
  •  温柔的废话
    2020-12-08 13:13

    The exception handling is different.

    You may want to check the following:

    private async void OnClick(object sender, RoutedEventArgs e)
    {
        Dispatcher.UnhandledException += OnUnhandledException;
        try
        {
            await Dispatcher.BeginInvoke((Action)(Throw));
        }
        catch
        {
            // The exception is not handled here but in the unhandled exception handler.
            MessageBox.Show("Catched BeginInvoke.");
        }
    
        try
        {
           await Dispatcher.InvokeAsync((Action)Throw);
        }
        catch
        {
            MessageBox.Show("Catched InvokeAsync.");
        }
    }
    
    private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        MessageBox.Show("Catched UnhandledException");
    }
    
    private void Throw()
    {
        throw new Exception();
    }
    

提交回复
热议问题