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.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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.
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);
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.