Click here to Skip to main content
15,918,108 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try to use parallel execution, in each foreach instead of waiting for GetByLastId function to return , but due to the await inside the GetByLastId function it is not response to the HttpClientResponse

What I have tried:

C#
foreach( DataRow item in dt.Rows)
 {
   var response = await RestApIHelper.GetByLastDate(item["Url"].ToString(), fetchAllFirstTime.token, Convert.ToDateTime(item["LastDate"]));

   var data = JsonConvert.DeserializeObject<List<createReservation>>(response);
  roomCreateOrUpdateViaAPI(data, "insert");
 }


GetByLastDate function

public static async Task<string> GetByLastDate(string specificUrl, string token, DateTime date)
{
   try
     {
       string fullUrl = baseUrl + specificUrl+ date;
       using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, fullUrl))
        {
         requestMessage.Headers.Add("access_token", token);
         HttpResponseMessage res = await policy.ExecuteAsync(() => client.SendAsync(requestMessage));
       using (HttpContent content = res.Content)
        {
          string data = await content.ReadAsStringAsync();
          if (data != null)
          {
            return data;
          }
        }
         return string.Empty;
      }
  }
Posted
Updated 6-Sep-21 23:00pm
v2

1 solution

I try to factorized like this

List<Task<string>> Tasks = new List<Task<string>>();


foreach( DataRow item in dt.Rows)
    {
     Tasks.Add( RestApIHelper.GetByLastDate(item["Url"].ToString(), fetchAllFirstTime.token, Convert.ToDateTime(item["LastDate"])) );
     }

     var responses = await Task.WhenAll(Tasks);
     foreach(string response in responses)
     {
       var data = JsonConvert.DeserializeObject<List<createReservation>>(response);
                       roomCreateOrUpdateViaAPI(data, "insert");
 }
 
Share this answer
 
v2
Comments
Richard MacCutchan 7-Sep-21 6:01am    
You already posted this question at How to refactor async for parallel execute[^]. Please do not repost.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900