gpt4 book ai didi

c# - 检索在 Task.WhenAll 抛出异常时起作用的内容

转载 作者:行者123 更新时间:2023-11-30 14:53:32 26 4
gpt4 key购买 nike

考虑

string[] pages;
Task [] asyncOps =
(from url in urls select DownloadStringAsync(url)).ToArray();
try
{
pages = await Task.WhenAll(asyncOps);
...
}
catch(Exception exc)
{
foreach(Task<string> faulted in asyncOps.Where(t => t.IsFaulted))
{
… // work with faulted and faulted.Exception
}
}

来自 https://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx .如何检索 DID 有效的页面?

或者更好的是,我怎样才能继续计算其余页面?

最佳答案

与其进行所有下载然后分别处理每个成功/错误,我认为如果您定义一个单独的“下载并处理错误”操作会更简洁:

Task [] asyncOps = 
(from url in urls select DownloadStringWithErrorCheckingAsync(url)).ToArray();
string[] pages = await Task.WhenAll(asyncOps);
var successfulPages = pages.Where(x => x != null);

...

private static Task<string> DownloadStringWithErrorCheckingAsync(string url)
{
try
{
return await DownloadStringAsync(url);
}
catch(Exception exc)
{
... // work with exc
return null;
}
}

关于c# - 检索在 Task.WhenAll 抛出异常时起作用的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com