A1RStack
A1RStack

Reputation: 85

Setting up a worker thread to continuously check a bool value of an object

I am running this code in a form, but when i start it, it freezes. This is because while keeps the other code from running. I want to setup a separate worker thread for this while task. However i do not know how to set up a worker thread for this specific task.

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

Upvotes: 1

Views: 71

Answers (1)

Heinzi
Heinzi

Reputation: 172408

Getting multi-threading right is not an easy task and should only be done if really necessary.

I have an alternative suggestion:

Your Controller game raises an event when the game is over:

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

The class containing startGame adds a handler to this event and closes the view when the event has been raised:

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

...

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

Upvotes: 3

Related Questions