我的代碼在所有任務完成之前繼續執行。任務。完成任務之前任務完成
我看過其他有類似問題的人,但看不到任何明顯的東西!
static Task MoveAccountAsync(MoverParams moverParams)
{
return Task.Run(() =>
{
Console.WriteLine("Moving {0}", moverParams.Account.Name);
moverParams.Account.Mover.RefreshRoom();
moverParams.Account.Mover.PathfindTo(moverParams.Room);
});
}
static async void MoveAccountsAsync(List<Account> accounts, int room)
{
List<Task> theTasks = new List<Task>();
foreach (Account account in accounts)
{
// Create a new task and add it to the task list
theTasks.Add(MoveAccountAsync(new MoverParams(account, room)));
}
await Task.WhenAll(theTasks);
Console.WriteLine("Finished moving.");
}
然後簡單地從靜態的主稱之爲:
MoveAccountsAsync(theAccounts, room);
幫助非常感謝!
乾杯,戴夫
您無法等待'async void'方法。它是隨時可以忘記的。除了事件處理程序外,總是使用'async Task'。在Main()中使用'.Wait()'作爲結果的'Task'。 –