'Why this async code is not running well in C#? [duplicate]
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)
Solution 1:[1]
The problem comes, because you don't (or better can't) await the result from the .ForEach() call, cause this overload just takes an Action and not a Func<Task>. Better would be:
var updateTasks = locations.Select(l => UpdateConfigAsync(l));
var results = await Task.WhenAll(updateTasks);
In that case you only create a lazy enumeration of tasks that should run. The next step is then to await all of these tasks by using the correct method (which would be Task.WhenAll() in this case).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oliver |
