【发布时间】:2011-07-15 07:35:33
【问题描述】:
我想知道在 wpf 应用程序中编写这种代码是否是正常的做法,以便我可以捕获异常并在 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));
}
});
因此,此代码将在 UI 线程上显示错误消息。如果这是“OK”那么为什么每个人都建议使用t.Wait();然后捕获任务中出现的所有异常?
PS,可能问题很愚蠢,但我没有找到适当的解释,并且对使用任务很陌生。
更新
This Joe Albahari's 文章帮助我理解了任务。
【问题讨论】:
标签: c# multithreading error-handling