views:

154

answers:

1

Hi all, 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) ? - 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) ! And thus m_TestThread.Start() generates an exception (StateException).

Stopping the thread with an Abort() doesn't solve it. If I put my 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.

Anybody has an idea ? All help highly appreciated ! Grtz E

+1  A: 

You can use Thread.Suspend and Thread.Resume for stopping/restarting the thread.

For checking the thread's status you can use Thread.ThreadState.

Vlad
See the subtitles for Suspend and Resume: "NOTE: This API is now obsolete."
Henk Holterman
THX all for the feedback. Unfortunately the ThreadState is not supported in the CF (http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx). I'll stick to the boolean, but I find it a very awkward way in handling (but maybe that's just me)
Ed