在这里,我正在创建一个模拟猜谜游戏的简单练习 windows phone 应用程序。我有一个运行游戏的while循环,直到用户猜出正确答案;我想要做的是在每个循环的开始,等待用户通过在文本框中按下回车来触发事件。我对这个想法很陌生,并且没有多线程方面的经验。我得到一个未授权访问异常,我不确定是什么原因造成的。
public partial class MainPage : PhoneApplicationPage
{
Random r;
int guess;
static AutoResetEvent autoEvent;
// Constructor
public MainPage()
{
InitializeComponent();
r = new Random();
autoEvent = new AutoResetEvent(false);
Thread t = new Thread(PlayGuessGame);
t.Start();
}
private void PlayGuessGame()
{
bool hasWon = false;
int secretNumber = r.Next(1, 3);
int tries = 1;
messageTextBox.Text = "Guess a number";
while (!hasWon)
{
autoEvent.WaitOne();
if (guess == secretNumber) //if user wins
{
messageTextBox.Text = "Congratulations! You've guess the correct number! It took {0} tries.";
}
else
{
tries++;
if (guess < secretNumber)
messageTextBox.Text = "Guess higher!";
else
messageTextBox.Text = "Guess lower!";
lastGuessTextBox.Text = guess.ToString();
}
}
}
private void guessTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
guess = int.Parse(guessTextBox.Text);
autoEvent.Set();
}
}
}