简体   繁体   中英

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. 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);
    });
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM