有没有办法等待TPL任务而不抛出异常? [英] Is there a way to Wait for a TPL Task without in throwing an exception?
本文介绍了有没有办法等待TPL任务而不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们中有些人喜欢代码的异常光的风格。不过,如果你等待TPL任务,任务抛出一个异常,它会抛出调用线程上的异常,以及。是否有一个(最好是标准)的方式来避免这种情况,只是检查异常的反应,当你把它找回来?
Some of us prefer to code in an exception-light style. However, if you wait for a TPL task, and the task threw an exception, it will throw an exception on the calling thread as well. Is there a (preferably standard) way to avoid this behaviour and just check the response for exceptions when you get it back?
推荐答案
你可以使用像Task.WaitAny:
You can use Task.WaitAny like:
var task = Task.Run(() =>
{
// ...
throw new Exception("Blah");
});
Task.WaitAny(task);
if (task.IsFaulted)
{
var error = task.Exception;
// ...
}
else if (task.IsCanceled)
{
// ...
}
else
{
// Success
}
这篇关于有没有办法等待TPL任务而不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文