设置工作线程以持续检查对象的bool值

时间:2016-10-13 10:30:30

标签: c# winforms

我在表单中运行此代码,但是当我启动它时,它会冻结。这是因为会阻止其他代码运行。我想为此任务设置一个单独的工作线程。但是,我不知道如何为此特定任务设置工作线程。

    public void startGame(Form sender) // Form that is being send is an mdiContainer
    {

        View view = new View();
        Controller game = new Controller(view);

        view.MdiParent = sender; //Here i tell the other form it's parent is sender
        view.Visible = true;

        //problem code
        while (true) 
 //This loop is supposed to keep checking if the game has ended and if it did, close the form view.
        {
            if(game.gameOver == true)
            {
                view.Close();
                break;
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

获得正确的多线程并非易事,只有在必要时才能完成。

我有另一种建议:

你的操作员game在游戏结束时举起一个事件:

class Controller
{
    ...

    public event EventHandler GameFinished;

    private bool gameOver;
    public bool GameOver 
    {
        get { return gameOver; }
        set
        {
            gameOver = value;
            if (gameOver)
                GameFinished?.Invoke(this, new EventArgs());
        }
    }
}

包含startGame的类为此事件添加处理程序,并在引发事件时关闭视图:

View view = new View();
Controller game = new Controller(view);

...

game.GameFinished += (sender, e) => { view.Close(); }