时间:2019-03-07 标签:c#CF
假设您有一个带有启动/停止线程的按钮的表单(不是暂停或中断,我真的需要停止线程!) 看看这段代码:
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 也不会清理。
有人有主意吗?高度赞赏所有帮助! 格茨 乙
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Thread.Suspend 和 < a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.resume.aspx" rel="nofollow noreferrer">Thread.Resume 用于停止/重新启动线程。
要检查线程的状态,您可以使用 Thread.ThreadState< /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.