.NET 什么时候任务被认为是错误的?
.NET When is a task considered as faulted?
我是 TPL 的新手,我想知道,当你遇到这样的问题时:
Task.Run(() =>{
// Some code here to call several APIs...
});
此任务何时被视为错误?当它们是内部抛出的异常时,没有被捕获?
您可以手动将此任务设置为故障吗?例如,如果您捕获到异常,您希望此任务出现故障,以便不执行后续任务?
感谢大家的帮助
是的,异常会导致失败状态(除非抛出 OperationCancelledException
,然后 IsCanceled
属性 变为真)。
您不能将任务直接设置为故障,除非直接使用 TaskCompletitionSource 源和 .SetException
方法。
但是抛出异常有什么问题?处理异常后你可以抛出它
Task.Run(() =>{
try
{
DoSomething();
}
catch(InvalidOperationException ex)
{
logging.Error("Something went wrong", ex);
// rethrow the same exception.
// Don't do: "throw ex" as it changes stack trace, making debugging harder
throw;
}
});
或者使用 C# 6.0 的 when language 构造来执行日志记录。
Task.Run(() =>{
try
{
DoSomething();
}
catch(InvalidOperationException ex) when (LogException(ex))
{
}
});
...
private bool LogException(ex)
{
logging.Error("Something went wrong", ex);
// returning true means, exception block will be executed
// returning false means, exception block won't be executed
return false;
}
这样,将执行日志记录,但不会捕获异常本身(并不会被等待任务捕获。
我是 TPL 的新手,我想知道,当你遇到这样的问题时:
Task.Run(() =>{
// Some code here to call several APIs...
});
此任务何时被视为错误?当它们是内部抛出的异常时,没有被捕获?
您可以手动将此任务设置为故障吗?例如,如果您捕获到异常,您希望此任务出现故障,以便不执行后续任务?
感谢大家的帮助
是的,异常会导致失败状态(除非抛出 OperationCancelledException
,然后 IsCanceled
属性 变为真)。
您不能将任务直接设置为故障,除非直接使用 TaskCompletitionSource 源和 .SetException
方法。
但是抛出异常有什么问题?处理异常后你可以抛出它
Task.Run(() =>{
try
{
DoSomething();
}
catch(InvalidOperationException ex)
{
logging.Error("Something went wrong", ex);
// rethrow the same exception.
// Don't do: "throw ex" as it changes stack trace, making debugging harder
throw;
}
});
或者使用 C# 6.0 的 when language 构造来执行日志记录。
Task.Run(() =>{
try
{
DoSomething();
}
catch(InvalidOperationException ex) when (LogException(ex))
{
}
});
...
private bool LogException(ex)
{
logging.Error("Something went wrong", ex);
// returning true means, exception block will be executed
// returning false means, exception block won't be executed
return false;
}
这样,将执行日志记录,但不会捕获异常本身(并不会被等待任务捕获。