简体   繁体   English

c#CF重新启动线程

[英]c# CF Restart a thread

Supose you have a form with a button that starts/stops a thread (NOT pausing or interrupting, I really need to stop the thread !) Check out this code: 假设您有一个带有按钮的表单,该按钮可以启动/停止线程(不要暂停或中断,我真的需要停止线程!)查看以下代码:

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 questions (remember CF): - How can I know if the thread is running (I cannot seem to access the m_pThreadState, and I've tried the C++ GetThreadExitCode(), it give false results) ? 2个问题(记住CF):-我如何知道线程是否正在运行(我似乎无法访问m_pThreadState,并且我尝试了C ++ GetThreadExitCode(),它给出了错误的结果)? - Most important question : if I have stopped the thread, I cannot restart it, most probably because the m_TestThread.m_fStarted is still set (and it is private so I cannot access it) ! -最重要的问题:如果我停止了线程,则无法重新启动它,这很可能是因为m_TestThread.m_fStarted仍然被设置(并且它是私有的,所以我无法访问它)! And thus m_TestThread.Start() generates an exception (StateException). 因此,m_TestThread.Start()会生成一个异常(StateException)。

Stopping the thread with an Abort() doesn't solve it. 使用Abort()停止线程无法解决问题。 If I put my m_TestThread = null; 如果我把我的m_TestThread = null; it works, but then I create a memory leak. 它可以工作,但随后会造成内存泄漏。 The GC doesn't clean up either, even if I wait for xx seconds. 即使我等待xx秒,GC也不会清理。

Anybody has an idea ? 有人有主意吗? All help highly appreciated ! 所有帮助高度赞赏! Grtz E 格茨

You can use Thread.Suspend and Thread.Resume for stopping/restarting the thread. 您可以使用Thread.SuspendThread.Resume来停止/重新启动线程。

For checking the thread's status you can use Thread.ThreadState . 要检查线程的状态,可以使用Thread.ThreadState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM