Click here to Skip to main content
15,920,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have await function, but I need to execute parallelly instead of one by one.

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");
  }

```
RestAPIHelper.GetByLastDate
```
C#
public static async Task<string> GetByLastDate(string specificUrl, string token, DateTime date)
        {
 
          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 7-Sep-21 0:21am

1 solution

Rather than awaiting each task, add them to a list and then use Task.WhenAll[^] to wait for them all to complete:
C#
public static async Task<List<createReservation>> GetByLastDate(string specificUrl, string token, DateTime date)
{
    string fullUrl = baseUrl + specificUrl+ date;
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, fullUrl))
    {
        requestMessage.Headers.Add("access_token", token);
        using (HttpResponseMessage res = await policy.ExecuteAsync(() => client.SendAsync(requestMessage)))
        {
            string data = await res.Content.ReadAsStringAsync();
            if (string.IsNullOrEmpty(data)) return null;
            return JsonConvert.DeserializeObject<List<createReservation>>(response);
        }
   }
}
C#
var tasks = new List<Task<List<createReservation>>>(dt.Rows.Count);

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

IEnumerable<List<createReservation>> results = await Task.WhenAll(tasks);
foreach (List<createReservation> data in results)
{
    roomCreateOrUpdateViaAPI(data, "insert");
}
 
Share this answer
 

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