来自Func<>的例外情况未被捕获(异步)

时间:2016-02-01 14:55:52

标签: c# exception asynchronous lambda async-await

我有以下代码(为简化此代码而简化)。显然,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异常块从未执行过?

1 个答案:

答案 0 :(得分:9)

由于该方法是异步的,因此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);
    }
}