我正在學習如何在控制檯應用程序中使用異步函數,但無法使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