在不停止GUI的情况下请求用户输入的最佳方法?

时间:2013-03-29 05:48:20

标签: c# winforms

我有一个简单的问答类型程序,有一些像这样的代码:

  private void AskQuestion(Question q)
        {
            questionbox.Text = q.GetQuestion();
            answering = true;

            while (answering == true)
            {

            }

                if (q.GetQuestion() == answerbox.Text)
                {
                    MessageBox.Show("well done");
                }

                else
                {
                    MessageBox.Show("nope");
                }

        }

回答只是我的一个切换,所以程序不会测试答案,直到用户输入答案并单击按钮。

我有一个按钮供用户点击,将其切换为false:

private void Answer_Click(object sender, EventArgs e)
        {
            answering = false; 
        }

这个想法是while循环暂停程序并在用户回答问题时退出,但它只是冻结整个事情。

我尝试用线程睡眠减慢它,然后我去看一个计时器观察变量,在一个新线程上尝试它,但线程不会互相交谈,所以我在这个愚蠢的情况下我我被卡住了。

请帮助程序员,并为我建议一个策略?

2 个答案:

答案 0 :(得分:0)

以下是示例:

        private void button2_Click(object sender, EventArgs e)
        {
            hey = true;
            Thread thread = new Thread(new ThreadStart(AskQuestion));
            thread.Start();
        }

        bool hey;
        void AskQuestion()
        {
            while (hey)
            { 

            }
            MessageBox.Show("Done");
        }

        private void answer_Click(object sender, EventArgs e)
        {
            hey = false;
        }

这会在按下answer_Click()时显示MessageBox。它不冻结。

答案 1 :(得分:0)

您可以将问题存储在一个字段中,并将答案逻辑放在Answer_Click

private Question _currentQuestion;

private void AskQuestion(Question q)
{
    _currentQuestion = q.GetQuestion();
    questionbox.Text =_currentQuestion;
}

private void Answer_Click(object sender, EventArgs e)
{
   if (_currentQuestion != null)
   {
      if (_currentQuestion == answerbox.Text)
      {
          MessageBox.Show("well done");
      }

      else
      {
          MessageBox.Show("nope");
      }
   }
}