任务。何时在任务完成之前完成

时间:2016-08-03 21:12:29

标签: c# .net asynchronous

我的代码在所有任务完成之前继续执行。

我已经看过有类似问题的其他人,但看不到任何明显的事情!

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中调用它:

MoveAccountsAsync(theAccounts, room);

非常感谢!

干杯, 戴夫

1 个答案:

答案 0 :(得分:3)

async void方法非常气馁,并经常(例如此处)签署问题。

因为你没有等待你的方法调用(并且你不能await因为它返回void),所以调用者不会等待所有的工作完成,然后再转到下一个语句

更改您的方法以返回Taskawait以解决问题。如果您从同步上下文(例如MoveAccountsAsync方法)调用Main,请使用Wait等待结果。但请注意,在某些情况下(例如,如果作为ASP.NET应用程序的一部分运行)可能会导致死锁。