Func的例外未捕获(异步) [英] Exception from Func<> not caught (async)
本文介绍了Func的例外未捕获(异步)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下一段代码(为了进行此复制而进行了简化)。显然,catch异常块将包含更多逻辑。
I'm having the following piece of code (simplified in order to make this repro). Obviously, the catch exception block will contain more logic.
我有以下代码:
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异常块?
Why is the catch exception block never executed?
推荐答案
未抛出异常,因为func的实际签名是 Funk< Task>
由于该方法是异步的。
The exception is not thrown because the actual signature of func is Funk<Task>
due to the method being async.
异步方法具有特殊的错误处理,只有在您等待该函数后才会引发异常。如果要支持异步方法,则需要具有第二个可以处理异步委托的函数。
Async methods have special error handling, the exception is not raised until you await the function. If you want to support async methods you need to have a 2nd function that can handle async delegates.
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);
}
}
这篇关于Func的例外未捕获(异步)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文