简体   繁体   中英

Handling exceptions inside Task

I wonder if its normal practice to write such kind of code in wpf application, so that i can catch exceptions and show some message on the UI:

Task.Factory.StartNew(() =>{                                              
    try
    {
        if (AuthenticationManager.Instance.Authenticate(username, password))
        {
            ... 
        }
        else
        {
            throw new AuthenticationException("Failed");
        }
    }
    catch (Exception ex)
    {
        Dispatcher.Invoke((Action)(() => txtWarning.Text = ex.Message));
    }
});

So this code will show error message on UI thread. If this is "OK" then why everyone suggests to use t.Wait(); and then catch all the exceptions that appeared in task?
PS, may be question is silly, but i didnt find proper explanation and am new to using of Tasks.

Update
This Joe Albahari's article helped me in understanding tasks.

The TPL makes a great effort to process exceptions for you and move them outside your Task(s).

So while you can catch them in the Task itself, that should be the exception to the rule.

In general you will indeed want to handle exceptions around the Wait point. In the case of showing messages on the GUI that eliminates the Dispatch problem immediately.

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