4

在这里,我正在创建一个模拟猜谜游戏的简单练习 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();
        }
    }

}
4

1 回答 1

3

您遇到的问题是因为您试图从不是由它创建的线程访问对象。因此,运行您的 PlayGuessGame() 的线程不应该在该沙箱中播放。你可以通过使用 MethodInvoder 来解决这个问题:

        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
            {
                this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Congratulations! You've guess the correct number! It took {0} tries."; }));

            }
            else
            {
                tries++;
                if (guess < secretNumber)
                    this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Guess higher!"; }));
                else
                    this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Guess lower!"; }));

                this.Invoke(new MethodInvoker(delegate { lastGuessTextBox.Text = guess.ToString(); }));
            }

        }
    }

我肯定会推荐 Brian Warshaw 的评论,这应该是一个事件驱动的 GUI。希望这会有所帮助,您可以在使用线程的其他地方使用它!

于 2013-12-20T14:38:24.740 回答