[英]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.