线程化:线程的可变访问和终止

时间:2011-01-19 21:28:35

标签: c# multithreading variables global-variables sharpdevelop

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

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个问题:

  • 我必须做些什么来使“提示”方法能够进行预告和回答?

  • 我是否正确地在分数变量上加1?

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

请告诉我要改变什么。我不知道编码的单词和术语,因为我刚开始几周前。请尽量保持清晰。

2 个答案:

答案 0 :(得分:0)

      static string preanswer;
      static decimal answer = 0;

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

答案 1 :(得分:0)

要等待线程,请使用Join()...这将告诉线程调用该函数哪个等待线程直到它加入:

ask.Join(int);
相关问题