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

标签 c# exception asynchronous lambda async-await

我有以下代码(经过简化以进行此重现)。显然,catch 异常 block 将包含更多逻辑。

我有以下代码:

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 异常 block 从未执行过?

最佳答案

没有抛出异常是因为func的实际签名是Funk<Task>由于方法是异步的。

异步方法有特殊的错误处理,直到你 await 函数才会引发异常。如果你想支持异步方法,你需要有第二个函数来处理异步委托(delegate)。

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);
    }
}

关于c# - 来自 Func<> 的异常未被捕获(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133605/

相关文章:

php - 在关闭函数中捕获异常

javascript - 如何使用 Selenium 正确等待列表滚动?

c# - 隐藏/显示 XAML 元素或阻止 LostFocus 事件

c# - 如何找到已被另一场比赛捕获的一场比赛?

c# - 如果您手动检测到线程错误,则抛出适当的异常

java.util.UnknownFormatConversionException : Conversion = '.'

java - 如何为 Android AsyncTask 类建模?

.net - AsyncCommand CanExecute 处理程序

c# - 在应用程序设计方面需要帮助

c# - 两次加载相同的程序集但版本不同