这是我在我的代码中做到的方式:在后面的WorkWorker DoWork活动中我做了:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_busy.WaitOne();
this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
this.Invoke(new MethodInvoker(delegate { label4.Text = mainUrl; }));
webCrawler(mainUrl, levelsToCrawl, e);
}
Run Code Online (Sandbox Code Playgroud)
然后在暂停按钮单击事件我做了:
private void button4_Click(object sender, EventArgs e)
{
_busy.Reset();
}
Run Code Online (Sandbox Code Playgroud)
在简历按钮单击事件我做了:
private void button5_Click(object sender, EventArgs e)
{
_busy.Set();
}
Run Code Online (Sandbox Code Playgroud)
但是当我点击开始这个过程时,它不起作用:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
this.Text = "Processing...";
label6.Text = "Processing...";
label6.Visible = true;
button2.Enabled = false;
checkBox1.Enabled = false;
checkBox2.Enabled = false;
numericUpDown1.Enabled = false;
button3.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)
只有当我单击恢复按钮时才会发生任何事情,然后当我单击暂停按钮时没有任何反应.
我希望当我单击开始进程按钮时,它会定期启动backgroundWorker,然后单击暂停按钮时它将暂停,恢复按钮将恢复.
我做错了什么 ?有人可以修复我的代码吗?
dba*_*lia 10
在BackgroundWorker线程代码中,您需要找到可以安全"暂停"执行的位置.ManualResetEvent是正确的代码方式.这篇文章可能会有所帮助: 有没有办法无限期地暂停一个帖子?
基本上,在您希望允许其暂停的工作线程代码中的几个选择点中,尝试插入:
_busy.WaitOne(Timeout.Infinite);
Run Code Online (Sandbox Code Playgroud)
当你想暂停(从你的主线程)你使用:
_busy.Reset();
Run Code Online (Sandbox Code Playgroud)
并恢复:
_busy.Set();
Run Code Online (Sandbox Code Playgroud)