我们中的一些人更喜欢以少量异常的方式编码。然而,如果您等待一个任务并行库(Task Parallel Library)任务,并且该任务抛出了异常,它也会在调用线程上抛出异常。是否有一种(最好是标准的)方法可以避免这种行为,只需在收到响应时检查异常即可?
我们中的一些人更喜欢以少量异常的方式编码。然而,如果您等待一个任务并行库(Task Parallel Library)任务,并且该任务抛出了异常,它也会在调用线程上抛出异常。是否有一种(最好是标准的)方法可以避免这种行为,只需在收到响应时检查异常即可?
var task = Task.Run(() =>
{
// ...
throw new Exception("Blah");
});
Task.WaitAny(task);
if (task.IsFaulted)
{
var error = task.Exception;
// ...
}
else if (task.IsCanceled)
{
// ...
}
else
{
// Success
}
如果没有引发异常,您无法等待失败的任务。但是,您可以等待该任务的后续任务,该任务仅在原始任务完成而未引发异常时完成:
public static Task SwallowExceptions(this Task task)
{
return task.ContinueWith(_ => { });
}
faultedTask.SwallowExceptions().Wait();
if (faultedTask.IsFaulted)
{
// handle exception
}
public static Task<T> SwallowExceptions<T>(this Task<T> task)
{
return task.ContinueWith(completedTask =>
completedTask.IsFaulted
? default(T)
: completedTask.Result);
}
很遗憾,这个功能不是内置的。使用以下解决方法:
myTask.ContinueWith(_ => { }, TaskContinuationOptions.ExecuteSynchronously).Wait();
myTask
完成时,它直接执行空委托。 - boot4life根据您所写的内容,捕获异常并检查IsFaulted
属性是否可能是您的解决方案?IsFaulted
var task1 = Task.Factory.StartNew(() =>
{
try
{
throw new MyCustomException("I'm bad, but not too bad!");
}
catch(Exception ex)
{
return new Result { Error = ex };
}
});
.ContinueWith(...)
来完成你的操作。 - Jens Kloster