簡體   English   中英

來自Func <>的異常未被捕獲(異步)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM