Задача. Когда все не ждут
Я учусь использовать асинхронные функции в консольном приложении, но не могу заставить задачу. Когда все будут ждать, пока все задачи не будут выполнены. Что не так со следующим кодом? Работает синхронно. Заранее спасибо.
static void Main(string[] args)
{
...
IncluiValores(...);
...
}
static async void IncluiValores(...)
{
Task<List<int>> res1 = att.GetAIDBAPI(att);
Task<List<int>> res2 = att.GetAIDBAPI(att2);
List<int>[] res = await Task.WhenAll(res1, res2);
...
}
ОБНОВЛЕНИЕ - Определение функции:
public async Task<List<int>> GetAIDBAPI(Attributes attributes)
{
List<int> results = null;
Connections client0 = new Connections();
HttpClient client = client0.OpenAPIConnection(attributes.User[0], attributes.Pwd, attributes.Server, attributes.Chave, attributes.Server2);
HttpResponseMessage response = await client.PostAsJsonAsync("api/Attributes/ID/Bulk", attributes);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
results = JsonConvert.DeserializeObject<dynamic>(content).ToObject<List<int>>();
}
else
{
var content = "[{-1}]";
var result = JsonConvert.DeserializeObject<dynamic>(content);
results = result.ToObject<List<int>>();
}
return results;
}
ОБНОВЛЕНИЕ 2 - Отдельный контекст
static void Main(string[] args)
{
AsyncContext.Run(() => MainAsync(args));
}
static async void MainAsync(string[] args)
{
await IncluiValores(...);
}
static async Task IncluiValores(...)
{
Task<List<int>> res1 = att.GetAIDBAPI(att);
Task<List<int>> res2 = att.GetAIDBAPI(att2);
List<int>[] res = await Task.WhenAll(res1, res2); // <- Error here
//Collection was modified; enumeration operation may not execute
...
}
//Tried to change to code below but it does not wait.
static async Task IncluiValores(...)
{
Task<List<int>> res1 = att.GetAIDBAPI(att);
Task<List<int>> res2 = att.GetAIDBAPI(att2);
await Task.WhenAll(res1, res2); // <- No error, just doesn't wait.
list.Add(res1.Result[0]);
}