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



我有一个与此类似的问题。但就我而言,它不是 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);
    });
}

通过在传递给 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 方法的调用周围,则可以在后台线程上处理异常。把它放在实际可能抛出的实际代码周围更有意义。

相关内容

最新更新