如何从线程中获取价值?

时间:2011-05-21 10:24:08

标签: multithreading

您好我正试图从我的线程中获取一个值,但似乎工作不那么找到我当然我发现我的代码结构不够稳定。我的代码我将我的线程类命名为“clsThreadCount”及以下是我的实施

public volatile bool Grab = false;
public volatile int count = 0;
public void Initialization(int i)
{
   count = i;
}
public void Play() 
{
   Grab = false;
   _shouldStop = false;
   ThreadTest();
}
public void Stop()
{
   _shouldStop = true;
   workerThread.Join(1);
   workerThread.Abort();
}
private void ThreadTest()
{
   workerThread = new Thread(DoWork);
   workerThread.Start();
   while (!workerThread.IsAlive) ;
}
private void DoWork()
{
   try
       {
          while (!_shouldStop)
          {
              if (Grab)
              {
                  count++;
                  Grab = false;
              }
          }
      }
      catch (Exception)
      {
          Play();
      }
      finally
      {
      }
 }

当我的程序(主菜单)开始运行时,我将在传递参数7时触发初始化函数

ObjThreadCount.Initialization(7); // count = 7
ObjThreadCount.Play();            // the thread are running
ObjThreadCount.Grab = true;       // the grab equal to true, count++ are trigger
Thread.Sleep(100);                // wait awhile
lblResult.Text = ObjThreadCount.count.ToString();  // sometime i can get count++ result (e.g. 8)
ObjThreadCount.Stop();            // thread stop

有时我的程序能够从线程中获得正确的计数,但有时则不能。 我意识到在我的while循环实现中有一些东西丢失了.. 像waitone或waitautoevent ..我可以忽略Thread.Sleep(100)??我应该在while循环中添加哪些合适的代码? 请帮帮我〜:S **抱歉在第一次上传时我忘记将“volatile”写入变量 谢谢..

1 个答案:

答案 0 :(得分:0)

如果是C#(以及C和java,可能还有C ++),则需要将_shouldStopGrab声明为volatile