c# - backgroundWorker 和 progressChanged 不工作

标签 c# progress-bar backgroundworker

我无法让进度条工作!如果我执行以下代码,即使代码被执行,该栏仍然是空的 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();
    }
}

预先感谢您的帮助

最佳答案

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

// Enable progress reporting
backgroundWorker1.WorkerReportsProgress = true;

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

关于c# - backgroundWorker 和 progressChanged 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9650908/

相关文章:

c# - 如何在 WPF 进度条中使用图像?

c# - 从线程更新数据绑定(bind)数据表是否安全?

vb.net - 等待多个Backgroundworkers完成

c# - WebBrowser 中的 HTML 与 Windows Phone 应用程序之间的通信

c# - 解析时使 DateTime 的天前导零可选

flash - 伪造进度条

c# - 在制作读取串行数据和绘制图形的 GUI 时实现线程

c# - 拒绝字符串变量中的字符串

c# - 使用 Moq 和 MSTest 测试异常的正确方法

安卓健康/能量棒