开发者

How to grab value from a thread?

Hi i am trying to grab a value from my threading but it seem work not so find to me course i found that my code structure are unstable enough..here is my code i name my thread class as "clsThreadCount" and below is my implementation

public volatile bool Grab = false;
public volatile int count = 0;
public void Initialization(int i)
{
   count = i;
}
public void Play() 
{
   Gra开发者_如何学Cb = 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
      {
      }
 }

when my program(main menu) are starting to run i will trigger the initialize function at pass the parameter as 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

sometime my program can able to get a right counting from the thread but sometime are not. i realize at my while loop implementation there are something are missing.. something like waitone or waitautoevent..can i ignore Thread.Sleep(100) ?? what are the suitable code should i add in the while loop ? Please help me~ :S ** sorry in the first upload i forgot to write down "volatile" into the variable thank you..


If C# (and C and java, and probably C++), you need to declare _shouldStop and Grab as volatile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜