【发布时间】:2014-02-21 07:51:05
【问题描述】:
我正在制作一个 Hangman Windows 窗体应用程序,到目前为止它运行良好,逻辑在那里,但我在 GUI 同步方面遇到了一个较小的问题。
现在我正在显示来自 GameForm.cs 的 UI,它反过来在单独的线程上实例化一个名为 GameRound 的类,现在问题有点奇怪,gameround 循环有效,问题是,它没有t 在调用它们时更新 UI 元素(在这种情况下,一个显示刽子手的图片框、一个显示模糊单词的文本框和一个显示已经猜到的字符的标签),而是在每次循环迭代后更新它们。但是我注意到,如果我在循环中插入一个MessageBox.Show(),那么它们将在消息框被调用时被更新。
我猜这是某种线程同步问题,表单不想在 Gameround 线程工作时更新,但我是一个完整的初学者程序员,所以我需要一些帮助!
这是 Gameround(Gameround.Start()) 的代码
public void Start()
{
Hangman hangman = new Hangman();
do
{
//Check if hangman is dead first
if (hangman.HangmanStep == 6) {
MessageBox.Show("You got hanged! RIP");
complete = true; }
bool w_reduceSticks = new bool();
string output = WordBuilder.ObscureWord(word);
HangManBox.Image = Drawing.Drawer.DrawHangMan(hangman.HangmanStep);
WordBox.Text = output;
GuessedLetters.Text = ReturnGuessedLetters(incorrectGuesses);
MessageBox.Show("");
//After guessing check if we've guessed all letters in the word
if (CompareLists(word.dontObscure, word.letters.Distinct().ToList()))
{
System.Threading.Thread.Sleep(5000);
complete = true;
break;
}
Thread readKeyThread = new Thread(InitReadKeyForm);
readKeyThread.Start();
readKeyThread.Join();
if (ReadKeyForm.Key == 2) {
w_reduceSticks = GuessWord();
}
else {
w_reduceSticks = GuessLetters(ReadKeyForm.Key);
}
if (w_reduceSticks)
{
hangman.HangmanStep++;
}
} while (!complete);
【问题讨论】:
-
由于
Thread.Sleep(2000);后面的break,您的代码的下部无法访问。但这是另一个问题。 -
对,这只是我在调试一些东西,我要编辑它。
标签: c# multithreading winforms