BackgroundWorker从不做任何事情?

时间:2015-03-27 19:57:22

标签: c# backgroundworker

这是我正在尝试执行的代码,但是单步执行我的代码我从未在我的窗体上显示progressbar1指示或更新任何进度。这是我第一次尝试让后台工作者正常运行,我所拥有的只是一个带有一个按钮的窗体,这就是项目中涉及的所有代码。

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    private int i = 0;

     public Form1()
    {
        InitializeComponent();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = false;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    }

    private void button1_Click(object sender, EventArgs e)
    {
            backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        ReadySteadyGo();
        worker.ReportProgress((i * 10));
        FinalizeAndFinish();
        worker.ReportProgress((i * 10));
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.Text = "Done!";
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Text = (e.ProgressPercentage.ToString() + "%");
    }

    private void ReadySteadyGo()
    {
        Thread.Sleep(100000);
    }
    private void FinalizeAndFinish()
    {
        Thread.Sleep(1000);
    }
}

2 个答案:

答案 0 :(得分:3)

您似乎正在使用Thread.Sleep()来模拟长时间运行的操作。根据您的代码示例,您应该考虑以下几点:

执行backgroundWorker1.RunWorkerAsync();时,它开始处理另一个线程。因此,如果您以交互方式进行调试而未在backgroundWorker1_DoWork方法中设置断点,则不太可能看到此代码执行。

Thread.Sleep(100000)执行时,它实质上意味着后台工作人员将暂停 100秒 - 因此您需要确保至少等待很长时间才能看到更新的UI 。

另外,根据Hans Passant的评论,请考虑以下事项:

  

你也看不到它做任何事情,没有必要分配   ProgressBar.Text属性,因为它不显示文本。设置Value   代替。

答案 1 :(得分:1)

我在Visual Studio中重新创建了您的示例,并且在backgroundWorker1_DoWork中遇到了断点,因此多线程工作正常,您只需要进行适当的处​​理吗?

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 1; i <= 100; i++)
        {
            backgroundWorker1.ReportProgress(i);
            Thread.Sleep(100);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }