在后台工作程序中暂停/恢复循环
我在Winform应用程序中的后台工作程序中有一个循环。
我刚刚使用了此代码,但在暂停后它不会恢复。
在主类我使用这个
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) { ...... ......
我不明白为什么暂停工作,而简历不起作用。 我错了什么?
我猜你想要的最好的猜测:
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(); } }