Unauthorizedaccessexception:如何等待来自用户的输入。 Windows Phone c#

时间:2013-11-08 18:02:47

标签: c# multithreading windows-phone

这里我正在创建一个模拟猜谜游戏的简单练习Windows手机应用程序。我有一个运行游戏的while循环,直到用户猜出正确的答案;我想要做的是在每个循环的开始,等待用户通过在文本框中按Enter键来触发事件。我是这个想法的新手,没有多线程经验。 我正在接受未经授权的访问,我不确定是什么导致它。

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

}

1 个答案:

答案 0 :(得分: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。希望这有帮助,你可以在其他地方使用你使用线程!