[英]c# CF Restart a thread
假設您有一個帶有按鈕的表單,該按鈕可以啟動/停止線程(不要暫停或中斷,我真的需要停止線程!)查看以下代碼:
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也不會清理。
有人有主意嗎? 所有幫助高度贊賞! 格茨
您可以使用Thread.Suspend和Thread.Resume來停止/重新啟動線程。
要檢查線程的狀態,可以使用Thread.ThreadState 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.