让我首先向您展示我的代码:

using System;
using System.Threading;
class MathQuiz
{
  static void Main() 
  {
   int score = 0;
   string preanswer;
   decimal answer = 0;
   Console.WriteLine("Welcome to Project5, a MathQuiz project.");
   Console.WriteLine("You will be asked 10 questions, and will have 30 seconds to read and answer each one.");
   Console.WriteLine("Press any key to begin.");
   Console.ReadKey(true);
   Console.WriteLine("What is 2 + 2?");
    Thread ask = new Thread (new ThreadStart (MathQuiz.prompt));
    ask.Start();
    Thread.Sleep(3000);
    //This is where I want to end the thread if it isn't already done.
    if (answer == 4)
    {
     score = score+1; //Here's where I don't know if my adding is correct.
    }
    Console.WriteLine("Press any key to move on to the next question!");
    Console.ReadKey(true);
  }

  static void prompt()
  {
   preanswer = (Console.ReadLine());
   if (!decimal.TryParse(preanswer, out answer))
  {
   Console.WriteLine("That wasn't even a number or decimal!");
  }
   else
       {
     answer = decimal.Parse(preanswer);
     }
  }
}

因此,当我尝试编译此代码时,我会在preanswer中获得CS0103错误,并在“提示”方法中回答。

这导致了3个问题:

  • 我到底需要做什么才能使Preanswer并回答“提示”方法?

  • 我是否正确地将1添加到分数变量上?

  • 如果线程正在运行,该如何终止? (在这种情况下,“询问”线程在输入答案之前不会结束。)

请告诉我要改变什么。我不知道编码单词和术语,因为我刚刚开始几周。请尽可能清楚。

有帮助吗?

解决方案

      static string preanswer;
      static decimal answer = 0;

      static void Main() 
      {
       int score = 0;
       //string preanswer;
       //decimal answer = 0;
...

等等

其他提示

要等待线程,请使用join()...这将告诉线程,要求该函数等待该线程,直到其返回为止:

ask.Join(int);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top