简体   繁体   中英

backgroundWorker and progressChanged not working

i cant get the progress bar to work! if i execute the following code the bar remains empty even if the code gets executed the ReportProgress doesnt seem to update anything..:

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

}

thanks in advance for your help

To initialize the BackgroundWorker, you must enable progress reporting and hook up your event handlers:

// Enable progress reporting
backgroundWorker1.WorkerReportsProgress = true;

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

I don't see where you set the WorkerReportsProgress property to true - that most likely is the problem:

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

I had the same problem. In AssemblyInfo.cs you should make this change for ComVisible.

[assembly: ComVisible(true)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM