使用列表元素作为内部函数参数创建Task-ArgumentOutOfRangeException

时间:2018-10-03 18:21:17

标签: c# asynchronous scheduled-tasks

这是我的课程:

class QuizShow
{
    List<Player> players;
    Task<GameResult>[] games;

    public QuizShow(List<Player> _players)
    {
        players = new List<Player>(_players);
        games = new Task<GameResult>[players.Count];
    }

    public void StartQuiz()
    {
        for(int i = 0; i < players.Count; ++i)
        {
            games[i] = Task.Run(() => Game(players[i]));
        }
    }

    public void WaitForEnd()
    {
        Task.WaitAll(games);
    }
}

对我来说,我很难理解的是,执行

时,方法StartQuiz上升了ArgumentOutOfRangeException
...
quiz.QuizStart();
quiz.WaitForEnd();
...

在Main中,而当我这样更改时:

public void StartQuiz()
{
    for(int i = 0; i < players.Count; ++i)
    {
        var player = players[i];
        games[i] = Task.Run(() => Game(player));
    }
}

不会发生此问题。
方法Game不会更改playersgames

此外,在调试时,只有当我不进入StartQuiz并执行该方法时,问题才会发生。

感谢您的解释。

0 个答案:

没有答案