1

我有一个问题,我正在使用backgroundWorker1.RunWorkerAsync()on button_click 方法,并且还使用backgroundWorker1_DoWork(),backgroundWorker1_ProgressChanged()事件,所有事件都在触发,但进度条没有刷新。这是我的代码:

private void btnMove_Click(object sender, EventArgs e)
        {

            try
           {

               backgroundWorker1.RunWorkerAsync();

                for (int i = 0; i < gdFiles.Rows.Count - 1; i++)
                {
                    // my process
                 }

              catch (Exception ex)
            {

            }

        }
     }

事件是

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;
            progressBar1.Refresh();
        }

任何人都可以请帮助解决这个问题......

4

3 回答 3

1

检查它的值backgroundWorker1.WorkerReportsProgress应该设置为true。波纹管工作和测试的例子:

public partial class Form1 : Form
{
    private BackgroundWorker bw = new BackgroundWorker();

    public Form1()
    {
        InitializeComponent();

        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

    }

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

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 1; i <= 100; i++)
        {

            bw.ReportProgress(i);
            Thread.Sleep(100);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bw.RunWorkerAsync();
    }
}
于 2013-04-17T06:20:43.633 回答
0

我试图复制你的问题,它在我的最终工作正常。确保 backgroundWorker1.ReposrtsProgress 设置为True。请参见下面的代码:

   '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;
        progressBar1.Refresh();
    }

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

另外,我认为您的“流程”应该在 DoWork 内部。

于 2013-04-17T06:30:59.213 回答
0

您不应该将文件移动逻辑移至 DoWork 部分吗?BackgroundWorker 的想法是从 UI 线程中移除繁重的东西。

于 2013-04-17T06:54:57.537 回答