I am using the following code in a .NET 6 console application.
using .....
List<Location> locations=GetLocations();
locations.ForEach(async l => await UpdateConfigAsync(l)); //Does Not Work
//foreach (Location l in locations) Task.WaitAll(UpdateConfig(l)); //Works fine
async Task UpdateConfigAsync(Location l)
{
await ConfigToDbAsync("storeProc1", HttpMethod.Get, "url1", l);
await ConfigToDbAsync("storeProc2", HttpMethod.Get, "url2", l);
await ConfigToDbAsync("storeProc3", HttpMethod.Get, "url3", l);
.....
}
async Task ConfigToDbAsync(string storeProc, HttpMethod method, string apiReq,
Location l)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (HttpRequestMessage request = new HttpRequestMessage(method, apiReq))
using (HttpResponseMessage response = await R365httpClient.SendAsync(request))
{
string json = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
using (SqlCommand command = new SqlCommand(storeProc, conn))
{
command.CommandTimeout = 300;
//Command Parameters...
await command.ExecuteNonQueryAsync();
}
}
response.EnsureSuccessStatusCode();
}
}
}
}
}
But it seems that locations.ForEach
does not wait for the task UpdateConfigAsync
(Nothing is sending to the database) and the program ends with no error.
Is there any wrong with the code?
Note: foreach (Location l in locations) Task.WaitAll(UpdateConfig(l));
works fine.
(I don't speak English)