How to include task parameter In array of tasks exception handling

吃可爱长大的小学妹 提交于 2019-12-06 04:38:59

Wrapping await in try/catch is fine, see: Catch an exception thrown by an async method. No big difference from my suggestion (capturing partition.Current and injecting into the ContinueWith continuation), except maybe it's a bit more efficient since no capturing is involved. Also it's a bit more readable and elegant I think, ContinueWith is kind of the "old" way of doing things (pre async/await).

Note that your example passes the burden of exception handling to the caller (who in this case calls _logger.LogError). You need to make sure that's what you want, as opposed to a catch-all embedded in the ForEachAsync code itself to handle the case where he caller does let an exception slip through. Something like:

while (partition.MoveNext()) 
{
    try
    {
        await body(partition.Current)
    }
    catch (Exception e)
    {
        // of course here you don't know the type of T (partition.Current)
        // or anything else about the operation for that matter
        LogError("error processing: " + partition.Current + ": " + e); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!