如果您有以下方法:
public async Task<string> GetTAsync(url)
{
return await httpClient.GetStringAsync(url);
}
public async Task<List<string>> Get(){
var task1 = GetTAsync(url1);
var task2 = GetTAsync(url2);
await Task.WhenAll(new Task[]{task1, task2});
// but this may through if any of the tasks fail.
//process both result
}
我该如何处理异常?我查看了HttpClient.GetStringAsync(url)方法的文档,它可能抛出的唯一异常似乎是ArgumentNullException。但至少我遇到禁止错误一次,并希望处理所有可能的异常。但我找不到任何具体的例外情况。我应该在这里捕获Exception异常吗?如果它更具体,我将不胜感激。 请帮忙,这非常重要。
答案 0 :(得分:1)
最后我认为如下:
public async Task<List<string>> Get()
{
var task1 = GetTAsync(url1);
var task2 = GetTAsync(url2);
var tasks = new List<Task>{task1, task2};
//instead of calling Task.WhenAll and wait until all of them finishes
//and which messes me up when one of them throws, i got the following code
//to process each as they complete and handle their exception (if they throw too)
foreach(var task in tasks)
{
try{
var result = await task; //this may throw so wrapping it in try catch block
//use result here
}
catch(Exception e) // I would appreciate if i get more specific exception but,
// even HttpRequestException as some indicates couldn't seem
// working so i am using more generic exception instead.
{
//deal with it
}
}
}
这是我最终想到的更好的解决方案。如果有更好的东西,我很乐意听到它。 我发布这个 - 只是其他人遇到同样的问题。