在WPF应用程序中调用Application.Current.Dispatcher.Invoke时在何处放置try-catch

时间:2019-04-26 14:26:22

标签: c# wpf

我有一个类似于this question的问题。但就我而言,它不是BeginIvnoke方法,而是Invoke方法。我需要将代码包装在try-catch语句中,但不确定确切的位置。

这是我的代码:

private void UpdateUI()
{
    Application.Current.Dispatcher.Invoke(() =>
    {
        if (SecurityComponent.CurrentLoggedUser != null)
        {
            var user = SecurityComponent.CurrentLoggedUser;
                m_userLabel.Text = user.Username + " - " + user.Role.Name;
        }                
        UpdateTerritories();
        ViewsIntegrationService.SetHmiMode(EHmiModes.Normal);
    });
}

1 个答案:

答案 0 :(得分:1)

通过在传递给Invoke方法的操作中添加try / catch语句,可以在UI线程上捕获异常:

private void UpdateUI()
{
    Application.Current.Dispatcher.Invoke(() =>
    {
        try
        {
            if (SecurityComponent.CurrentLoggedUser != null)
            {
                var user = SecurityComponent.CurrentLoggedUser;
                m_userLabel.Text = user.Username + " - " + user.Role.Name;
            }
            UpdateTerritories();
            ViewsIntegrationService.SetHmiMode(EHmiModes.Normal);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    });
}

如果将try / catch放在对Invoke方法的调用周围,则可以在后台线程上处理异常。将它放在可能实际抛出的实际代码周围更有意义。

相关问题