Reputation: 4929
I have a question similar to this question. But in my case, it is not the BeginIvnoke method, it is the Invoke method. I need to wrap my code in the try-catch statement, but not sure exactly where to put it.
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);
});
}
Upvotes: 1
Views: 961
Reputation: 169160
You catch the exception on the UI thread by adding the try/catch statement in the action that you pass to the Invoke
method:
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. It makes more sense to put it around the actual code that may actually throw.
Upvotes: 3