[英]Exception from Func<> not caught (async)
我有以下一段代码(简化为了使这个repro)。 显然,catch异常块将包含更多逻辑。
我有以下代码:
void Main()
{
var result = ExecuteAction(async() =>
{
// Will contain real async code in production
throw new ApplicationException("Triggered exception");
}
);
}
public virtual TResult ExecuteAction<TResult>(Func<TResult> func, object state = null)
{
try
{
return func();
}
catch (Exception ex)
{
// This part is never executed !
Console.WriteLine($"Exception caught with error {ex.Message}");
return default(TResult);
}
}
为什么catch异常块从未执行过?
不抛出异常,因为func的实际签名是Funk<Task>
因为该方法是异步的。
异步方法具有特殊的错误处理,在等待该函数之前不会引发异常。 如果要支持异步方法,则需要具有可以处理异步委托的第二个函数。
void Main()
{
//This var will be a Task<TResult>
var resultTask = ExecuteActionAsync(async() => //This will likely not compile because there
// is no return type for TResult to be.
{
// Will contain real async code in production
throw new ApplicationException("Triggered exception");
}
);
//I am only using .Result here becuse we are in Main(),
// if this had been any other function I would have used await.
var result = resultTask.Result;
}
public virtual async TResult ExecuteActionAsync<TResult>(Func<Task<TResult>> func, object state = null)
{
try
{
return await func().ConfigureAwait(false); //Now func will raise the exception.
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught with error {ex.Message}");
return default(TResult);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.