我的代码在所有任务完成之前继续执行。任务。完成任务之前任务完成
我看过其他有类似问题的人,但看不到任何明显的东西!
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'。 –