在后台工作暂停/继续循环 [英] Pause/Resume loop in Background worker
本文介绍了在后台工作暂停/继续循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在后台工作在WinForm应用程序的循环。
I have a loop in Background worker in a Winform Application.
我只是用这个 code 但不会暂停后重新开始。
I Just used this Code but it won't resume after the Pause.
在我使用这个主类
System.Threading.ManualResetEvent _busy =新System.Threading.ManualResetEvent(假);
然后在我开始单击我写这样的:
Then in My Start Click I wrote this:
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我写这个:
Then in backgroundworker doWork I wrote this:
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)
{
......
......
我不明白为什么暂停工作,同时恢复不起作用。难道我错了什么东西?
I can't understand why pause works while resume doesn't work. Did I wrong something?
推荐答案
我所能为你想要的猜测:
My best guess for what you want:
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();
}
}
这篇关于在后台工作暂停/继续循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文