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.");
}
Then simply calling it from static main:
MoveAccountsAsync(theAccounts, room);
Help much appreciated!
Cheers, Dave
async void
methods are highly discouraged and often times (e.g. here) sign of an issue.Because you're not awaiting your method call (and you can't
await
it because it returnsvoid
) caller will not wait for all the work to finish before moving on to the next statement.Change your method to return
Task
andawait
it to fix the problem. If you're calling intoMoveAccountsAsync
from synchronous context (e.g.Main
method) useWait
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.