任务任务完成之前的所有完成时间

本文关键字:任务 时间 | 更新日期: 2023-09-27 18:00:16

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

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

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);

非常感谢您的帮助!

干杯,Dave

任务任务完成之前的所有完成时间

async void方法非常不受欢迎,并且经常(例如此处)出现问题迹象。

因为您没有等待方法调用(也不能await,因为它返回void),所以调用者不会等待所有工作完成后再转到下一条语句。

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