簡體   English   中英

異步任務的異常處理

[英]Exception Handling on async tasks whenall

我正在對多個任務使用異步/等待作為參考。

public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

是否有可能在特定索引上捕獲異常。 例如,當DoSomething在i上引發異常時,我可以捕獲該特定索引嗎?

一種簡單的方法是捕獲異常,在異常的數據上插入索引信息,然后重新拋出:

int[] ids = new[] {1, 2, 3, 4, 5};
await Task.WhenAll(ids.Select(i =>
{
    try
    {
        return DoSomething(1, i, null);
    }

    catch (Exception ex)
    {
        ex.Data["FailedIndex"] = i; // Information about failed index
        throw;
    }
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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