简体   繁体   中英

C# visual studio 2010 background worker, report progress

Hey I'm trying to get my background worker to send a parameter back to the main thread in my form whenever it changes..

Within the method that the background worker runs I have this

worker.ReportProgress(p);

p is the variable in a for loop that is running

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        label6.Text = e.ToString();
    }

I'm trying to get this label text to change to p as the background worker goes through the loop.

Thanks for any help!! :)

ReportProgress takes two arguments :

  1. ProgressPercentage (INTEGER)
  2. UserState (Object)

If you don't care about the progress percentage you can send 0 and not use it :

worker.ReportProgress(0, p);

Or you can use the single argument overload and only send the progress percentage.

In your handler the ProgressChangedEventArgs has a couple of properties you have to use. To get the progress percentage value you access it as

myPercentLabel.Text = e.ProgressPercentage.ToString;

to get your user data ( p ) you have to access it as :

label6.Text = e.UserState.ToString;

To send more complex data you can send any type of object or structure in the UserState as long as you cast it properly in the handler. In either case you have to access either the ProgressPercentage or the UserState property of e .

You're likely to run into a few issues with this. First up, if your loop in the background worker is relatively quick, the value can change too quickly for your label to keep up. Second, the label may not necessarily refresh immediately every time the text is set, so it may skip over some values. Last, I believe what you actually want is e.UserState.ToString() instead of just e.ToString();

You must pass

worker.ReportProgress((int)(p*100.0/loopMaxValue));

then use

label6.Text = e.ProgressPercentage.ToString();

instead of

label6.Text = e.ToString();

I got it!

did this...

    label6.Text = e.UserState.ToString();

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