簡體   English   中英

在WPF應用程序中調用Application.Current.Dispatcher.Invoke時在何處放置try-catch

[英]Where to put try-catch when calling Application.Current.Dispatcher.Invoke in WPF application

我有一個與此問題類似的問題 但就我而言,它不是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方法的Invoke周圍,​​則可以處理后台線程上的異常。 將它放在可能實際拋出的實際代碼周圍更有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM