[英]Where to put try-catch when calling Application.Current.Dispatcher.Invoke in WPF application
I have a question similar to this question . 我有一个与此问题类似的问题 。 But in my case, it is not the BeginIvnoke method, it is the Invoke method. 但就我而言,它不是BeginIvnoke方法,而是Invoke方法。 I need to wrap my code in the try-catch statement, but not sure exactly where to put it. 我需要将代码包装在try-catch语句中,但不确定确切的位置。
Here is my code: 这是我的代码:
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);
});
}
You catch the exception on the UI thread by adding the try/catch statement in the action that you pass to the Invoke
method: 通过在传递给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);
}
});
}
If you put the try/catch around the call to the Invoke
method, you get to handle the exception on the background thread. 如果将try / catch放在对Invoke
方法的Invoke
周围,则可以处理后台线程上的异常。 It makes more sense to put it around the actual code that may actually throw. 将它放在可能实际抛出的实际代码周围更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.