2016-10-13 40 views
1

我在窗體中運行此代碼,但是當我啓動它時,它會凍結。這是因爲保持其他代碼不運行。我想爲此任務設置單獨的工作線程。但是我不知道如何爲這個特定的任務設置一個工作線程。設置工作線程連續檢查對象的布爾值

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

請勿使用循環。使用'EventWaitHandle' – Dai

回答

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