我在Winform应用程序中的后台工作程序中有一个循环。
我刚刚使用了这个Code,但在暂停后它不会恢复。
在主课程中我使用此
System.Threading.ManualResetEvent _busy = new System.Threading.ManualResetEvent(false);
然后在我的开始点击我写了这个:
if (!backgroundWorker1.IsBusy)
{
MessageBox.Show("Not Busy"); //Just For Debugg
_busy.Set();
Start_Back.Text = "Pause";
backgroundWorker1.RunWorkerAsync(tempCicle);
}
else
{
_busy.Reset();
Start_Back.Text = "Resume";
}
btnStop.Enabled = true;
然后在backgroundworker doWork中我写了这个:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
m_addTab addTabsInvoke = addTabUrl2;
Invoke(addTabsInvoke, "http://www.google.com");
foreach (something)
{
_busy.WaitOne();
if (backgroundWorker1.CancellationPending)
{
return;
}
if (tabs.InvokeRequired)
{
......
......
我无法理解为什么暂停有效而简历不起作用。我错了什么?
答案 0 :(得分:10)
我对你想要的最好的猜测:
void ResumeWorker() {
// Start the worker if it isn't running
if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(tempCicle);
// Unblock the worker
_busy.Set();
}
void PauseWorker() {
// Block the worker
_busy.Reset();
}
void CancelWorker() {
if (backgroundWorker1.IsBusy) {
// Set CancellationPending property to true
backgroundWorker1.CancelAsync();
// Unblock worker so it can see that
_busy.Set();
}
}