我正在学习如何在控制台应用程序中使用异步函数,但无法使Task.WhenAll等待所有任务完成。下面的代码有什么问题?它同步工作。先谢谢你。Task.WhenAll不等待
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]);
}
GetAIDBAPI的定义是什么样的? – BoltClock
包含定义。 – Gabriel
您的呼叫代码位于何处?如果它在Main中,它将无法正常工作。如果它使用自己的异步方法,那么该方法的任务是如何开始的? – BoltClock