c#CF重新启动一个线程

时间:2010-03-22 13:04:29

标签: c# compact-framework multithreading

假设您有一个带有启动/停止线程的按钮的表单(不暂停或中断,我真的需要停止线程!) 看看这段代码:

Constructor()
{
  m_TestThread = new Thread(new ThreadStart(ButtonsThread));
  m_bStopThread = false;
}

ButtonClick
{
  // If the thread is not running, start it
  m_TestThread.Start();
  // If the thread is running, stop it
  m_bStopThread = true;
  m_TestThread.Join();
}

ThreadFunction()
{
  while(!m_bStopThread)
  {
    // Do work
  }
}

2个问题(记住CF): - 我怎么知道线程是否正在运行(我似乎无法访问m_pThreadState,我尝试过C ++ GetThreadExitCode(),它会给出错误的结果)? - 最重要的问题:如果我已经停止了线程,我无法重新启动它,很可能因为m_TestThread.m_fStarted仍然设置(并且它是私有的,所以我无法访问它)!因此m_TestThread.Start()会生成一个异常(StateException)。

使用Abort()停止线程无法解决问题。如果我把我的m_TestThread = null;它工作,但后来我创建了内存泄漏。即使我等了xx秒,GC也不会清理。

有人有想法吗?所有帮助高度赞赏! Grtz ë

1 个答案:

答案 0 :(得分:1)

您可以使用Thread.SuspendThread.Resume来停止/重新启动主题。

要检查线程的状态,您可以使用Thread.ThreadState

相关问题