Task.WhenAll finishing before Tasks have completed

2019-07-23 19:24发布

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

1条回答
仙女界的扛把子
2楼-- · 2019-07-23 19:41

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 returns void) caller will not wait for all the work to finish before moving on to the next statement.

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.

查看更多
登录 后发表回答