Reputation: 727
if you have the following methods:
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
}
How can I handle exception? I looked at the documentation for HttpClient.GetStringAsync(url) method and the only exception it might throw seems to be ArgumentNullException. But at least I run into forbidden error once and would like to handle all possible exception. But i can't find any specific exceptions. Should I catch just Exception exception here? I would appreciate if it is more specific. Please help, its really important.
Upvotes: 2
Views: 11757
Reputation: 727
Finally i figured it as follows:
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
}
}
}
This is a much better solution i finally figured. If there is something better, i would love to hear about it. I'm posting this -just case someone else runs into the same issue.
Upvotes: 1