tasks for httpclient

Dondon510 221 Reputation points
2022-09-11T02:51:41.673+00:00

Hi All,

I need to control HttpClient async task, but I don't know how to add the task if it has a return value that need to be managed

List<Task> tasks = new List<Task>();  
  
var client = new HttpClient(clientHandler);  
var url = new Uri($"https://iot.truphone.com/api/v2.2/sims/?per_page=500&page={pageNo}");  
  
client.DefaultRequestHeaders.Accept.Clear();  
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", token);  
  
var response = await client.GetAsync(url);        --> HOW TO ADD TO tasks HERE  
HttpStatusCode statusCode = response.StatusCode;  
  
if (statusCode == HttpStatusCode.OK)  
{  
     response.EnsureSuccessStatusCode();  
     string res = await response.Content.ReadAsStringAsync();     
     if (response.IsSuccessStatusCode)  
     {  
        // some processes starts here!  

 
     }  
}  
  
await Task.WhenAll(tasks);    --> I want to wait here until all the tasks completely done  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-09-11T15:04:37.737+00:00

    Because you are using await, line 25 won’t execute until the “tasks” have completed. Because the read response can not be called get completes, you can not overlap the tasks.

    So no await is required.

    0 comments No comments

  2. Dondon510 221 Reputation points
    2022-09-11T15:38:00.077+00:00

    Hi @Bruce (SqlWork.com)

    do you mean I should not use await like the below?

                     List<Task> tasks = new List<Task>();  
    
                    var response = client.GetAsync(url).Result;            --> how to add task here?  
                    HttpStatusCode statusCode = response.StatusCode;  
    
                    if (statusCode == HttpStatusCode.OK)  
                    {  
                        response.EnsureSuccessStatusCode();  
                        string res = response.Content.ReadAsStringAsync().Result;  
                    }  
    

    at bottom, I still use:

    await Task.WhenAll(tasks);

    0 comments No comments

  3. Bruce (SqlWork.com) 55,601 Reputation points
    2022-09-12T17:37:46.25+00:00

    it is still unclear what you are trying to do. you have two tasks. open connection to website (GetAsync), read response. the second task can not be started until the first one completes. you original code was correct, but there was no need for line 25.

    0 comments No comments