Unauthorizedaccessexception:如何等待来自用户的输入. Windows
发布时间:2020-12-14 05:24:50 所属栏目:Windows 来源:网络整理
导读:在这里,我正在创建一个模拟猜谜游戏的简单练习 Windows手机应用程序.我有一个运行游戏的while循环,直到用户猜出正确的答案;我想要做的是在每个循环的开始,等待用户通过在文本框中按Enter键来触发事件.我是这个想法的新手,没有多线程经验. 我正在接受未经授权
在这里,我正在创建一个模拟猜谜游戏的简单练习
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(); } } } 解决方法
您遇到的问题是因为您尝试从未创建的线程访问对象.因此,运行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.希望这有帮助,你可以在其他地方使用你使用线程! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- windows – 使用Topshelf安装后无法在服务下看到我的服务
- 以编程方式在Windows 8上排序文件夹
- \r与\n的区别:
- 2018-2019-2 《网络对抗技术》Exp3免杀原理与实践 20165222
- windows-phone-8 – Windows Phone 8应用程序的临时分发
- windows-server-2003 – Windows文件服务器性能调优
- windows-server-2008-r2 – 使用SAN LUN的跨区卷的注意事项
- 怎么删除服务中的mysql服务
- 启动AutoCAD时自动加载.NET开发的DLL
- windows – 使用Delphi 7中的WMI进行内存泄漏
推荐文章
站长推荐
- windows – 如何使CStatic控件(MFC)透明?
- windows – 链接:.a,.lib和.def文件
- xaml – 如何检测方向变化和更改布局?
- windows-server-2008 – GPO中计算机配置和用户配
- 批处理文件 – 是否可以使用批处理文件Windows X
- Windows运行时 – 什么是WinRT语言预测?
- 为什么限制在我的WiX / MSI设置中使用自定义操作
- windows-7 – 为什么Windows 7兼容模式有Windows
- Windows Server 2012 R2 DataCenter列出指定服务
- iis – Windows 7相当于“Add-WindowsFeature”
热点阅读