c# CF Restart a thread
Posted
by Ed
on Stack Overflow
See other posts from Stack Overflow
or by Ed
Published on 2010-03-22T13:04:29Z
Indexed on
2010/03/22
13:31 UTC
Read the original article
Hit count: 394
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
© Stack Overflow or respective owner