我有這樣的代碼暫停和恢復線程:暫停和恢復線程
public partial class frmMain : Form
{
(...)
ManualResetEvent wait_handle = new ManualResetEvent(true);
(...)
}
private void frmMain_Shown(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TheLoop));
}
private void TheLoop(object stateinfo)
{
bool hasInfo = true;
while (doLoop)
{
wait_handle.WaitOne();
bool hasLines = GetInfo();
if (hasLines)
{
//Consuming time Operation 1
System.Threading.Thread.Sleep(7000);
if (CurrentLine < line.Count - 1)
CurrentLine++;
else
{
bool hasInfo2 = GetInfo2();
if (hasInfo2)
{
//Consuming time Operation 2
System.Threading.Thread.Sleep(7000);
}
CurrentLine = 0;
}
}
else
System.Threading.Thread.Sleep(40000); //Wait to query again
}
}
private void btnPauseResume_Click(object sender, EventArgs e)
{
if (btnPauseResume.Text == "Pause")
{
btnPauseResume.Text = "Resume";
wait_handle.Reset();
}
else
{
btnPauseResume.Text = "Pause";
wait_handle.Set();
}
}
上面的代碼顯示了一個週期的信息,它的工作原理髮現暫停和恢復「第一耗時操作」,但沒有按如果我在第二個消費時間操作中按下按鈕暫停線程,則這個繼續,當第一個再次出現時,它會在那裏暫停。
我在這裏錯過了什麼? Thx
更完整的代碼可能會有所幫助。 – CrazyDart
感謝編輯CrazyDart,我讀了多個wait_handle.WaitOne();每次我需要暫停或恢復一個線程時都需要,我試圖在Operation 2之前添加一個,但沒有工作。 – Somebody
在消費時間操作中,我從數據庫中讀取並使用調用在GUI中設置值。這就是全部,所以我不認爲這會成爲問題。 – Somebody