如何暂停和恢复一个BackgroundWorker? [英] How to pause and resume a BackgroundWorker?

查看:267
本文介绍了如何暂停和恢复一个BackgroundWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我做到了在我的代码:
在BackgroundWorker的DoWork的事件我所做的:

This is how i did it in my code: In the backgroundworker dowork event i did:

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);


        }



然后在暂停按钮单击事件我所做的:

Then in the pause button click event i did:

private void button4_Click(object sender, EventArgs e)
        {
            _busy.Reset();
        }

在简历按钮单击事件我所做的:

In the resume button click event i did:

private void button5_Click(object sender, EventArgs e)
        {
            _busy.Set();
        }



但其不工作当我点击启动流程:

But its not working when i click to start the process:

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;
        }



就只是当我点击恢复按钮,然后在过程开始时,我点击发生暂停按钮没有发生。

Nothing happen only when i click the resume button the process start then when i click the pause button nothing happen.

我想,当我clcik启动过程按钮,它会点击暂停按钮,它会暂停和恢复按钮时启动BackgroundWorker的定期再它会恢复。

I want that when i clcik the start process button it will start the backgroundworker regular then when clicking the pause button it will pause and the resume button it will resume.

我做了什么错?谁能解决我的代码?

What did i do wrong ? Can someone fix my code ?

推荐答案

在您的BackgroundWorker的线程代码,你需要找到安全的地方暂停执行。 ManualResetEvent的是编写正确的方式。这等后期可能会帮助:
有什么办法?无限期暂停线程

In your BackgroundWorker thread code, you need to find places that are safe to "pause" execution. The ManualResetEvent is the right way to code. This other post might help: Is there a way to indefinitely pause a thread?

基本上,在几个点选择在你的工作线程的代码要让它暂停,请尝试将:

Basically, in a few choice points in your worker thread code where you want to allow it to pause, try inserting:

_busy.WaitOne(Timeout.Infinite);



而当要暂停(从你的主线程)使用:

And when you want to pause (from your main thread) you use:

_busy.Reset();

和恢复:

_busy.Set();

这篇关于如何暂停和恢复一个BackgroundWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆