来自Func <>的异常未被捕获(异步)

Sam*_*tte 4 c# lambda asynchronous exception async-await

我有以下一段代码(简化为了使这个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么catch异常块从未执行过?

Sco*_*ain 10

不抛出异常,因为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);
    }
}
Run Code Online (Sandbox Code Playgroud)