【问题标题】:backgroundWorker and progressChanged not workingbackgroundWorker 和 progressChanged 不起作用
【发布时间】:2012-03-10 22:54:15
【问题描述】:

我无法让进度条工作!如果我执行以下代码,即使代码被执行,该栏仍为空,ReportProgress 似乎没有更新任何内容..:

namespace GPUZ_2

{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        GPUZdata test = new GPUZdata
        {
        };

        //invio l'oggetto al thread backgroundworker
        backgroundWorker1.RunWorkerAsync(test);
    }


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //
        // e.Argument always contains whatever was sent to the background worker
        // in RunWorkerAsync. We can simply cast it to its original type.
        //
        GPUZdata argumentTest = e.Argument as GPUZdata;




        argumentTest.OneValue = 6;
        Thread.Sleep(2000);
        backgroundWorker1.ReportProgress(50);
        argumentTest.TwoValue = 3;
        Thread.Sleep(2000);
        backgroundWorker1.ReportProgress(100);


        //
        // Now, return the values we generated in this method.
        // Always use e.Result.
        //
        e.Result = argumentTest;
    }


    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

         // Receive the result from DoWork, and display it.

        GPUZdata test = e.Result as GPUZdata;
        this.Text = test.OneValue.ToString() + " " + test.TwoValue.ToString();

     }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Change the value of the ProgressBar to the BackgroundWorker progress.
        progressBar1.Value = e.ProgressPercentage;
        // Set the text.
        this.Text = e.ProgressPercentage.ToString();
    }
}

}

提前感谢您的帮助

【问题讨论】:

  • 您需要做的最重要的事情:在 RunWorkerCompleted 事件中从不忽略 e.Error 属性。
  • 好的,谢谢,我只是在学习所需代码最少的教程

标签: c# progress-bar backgroundworker


【解决方案1】:

要初始化 BackgroundWorker,您必须启用进度报告并连接您的事件处理程序:

// Enable progress reporting
backgroundWorker1.WorkerReportsProgress = true;

// Hook up event handlers
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;

【讨论】:

  • 谢谢!这解决了我的问题,我不明白我必须连接事件处理程序才能使其运行,谢谢:)
【解决方案2】:

我看不到您将 WorkerReportsProgress 属性设置为 true 的位置 - 这很可能是问题所在:

backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync(test);

【讨论】:

  • 我尝试将这一行添加到代码中但没有成功,无论如何我使用 Visual Studio GUI 启用了进度报告,不一样吗?
【解决方案3】:

我遇到了同样的问题。在 AssemblyInfo.cs 中,您应该对 ComVisible 进行此更改。

[assembly: ComVisible(true)]

【讨论】:

  • 您能否提供更多详细信息来证明您的回答。像为什么 ComVisible(true) 解决问题等等。
猜你喜欢
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多