问题描述
在所有任务完成之前,我的代码将继续执行.
My code is continuing to execute before all tasks have been completed.
我看过其他有类似问题的人,但是看不到任何明显的东西!
I've had a look at other people with a similar problem but can't see anything obvious!
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.");
}
然后简单地从静态main调用它:
Then simply calling it from static main:
MoveAccountsAsync(theAccounts, room);
非常感谢您的帮助!
干杯,戴夫
推荐答案
异步void
方法,并且经常(例如在此处)出现问题的迹象.
async void
methods are highly discouraged and often times (e.g. here) sign of an issue.
因为您不等待方法调用(并且因为返回 void
而不能等待
),所以调用者将不会等待所有工作完成之前移至下一条语句.
Because you're not awaiting your method call (and you can't await
it because it returns void
) caller will not wait for all the work to finish before moving on to the next statement.
更改您的方法以返回 Task
并 await
来解决该问题.如果您要从同步上下文(例如 Main
方法)调用 MoveAccountsAsync
,请使用 Wait
等待结果.但是请注意,在某些情况下(例如,如果作为ASP.NET应用程序的一部分运行)可能会导致死锁.
Change your method to return Task
and await
it to fix the problem. If you're calling into MoveAccountsAsync
from synchronous context (e.g. Main
method) use Wait
to wait on the results. But be aware that in certain conditions (e.g. if run as part of ASP.NET application) that might cause deadlocks.
这篇关于Task.WhenAll在任务完成之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!