BackgroundWorker.ProgressChanged Event

G

Guest

Hi,

My Windows application has a time-consuming operation which I'd like to run
on a separate thread so that the UI can remain responsive.

I'm thinking of using the BackgroundWorker class and have referred to a
relevant MSDN article at:

http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

However, I notice that "ProgressChangedEventArgs" of the
"backgroundWorker1_ProgressChanged" event handler only has a parameter
"ProgressPercentage". When I give progress updates I'd like to give more
information by, for example, displaying text in a text box (eg. "Found 3
pending customer orders"), instead of simply incrementing a progress bar. Now
how can I accomplish this?



ywb.
 
B

Barry Kelly

WB said:
My Windows application has a time-consuming operation which I'd like to run
on a separate thread so that the UI can remain responsive.
[snip]
When I give progress updates I'd like to give more
information by, for example, displaying text in a text box (eg. "Found 3
pending customer orders"), instead of simply incrementing a progress bar. Now
how can I accomplish this?

You'll have to update the textbox on the main UI thread. You can marshal
the action over to the UI thread with ISynchronizeInvoke.Invoke /
Control.Invoke. The easiest way to send all the code across is via an
anonymous delegate. For example:

---8<---
using System;
using System.Windows.Forms;
using System.Threading;

class App
{
delegate void Method();

static void Main()
{
Form f = new Form();
f.Text = "Form";

ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(2000);
f.Invoke((Method) delegate
{
f.Text = "Changed!";
});
});

Application.Run(f);
}
}
--->8---

-- Barry
 
M

Mehdi

However, I notice that "ProgressChangedEventArgs" of the
"backgroundWorker1_ProgressChanged" event handler only has a parameter
"ProgressPercentage". When I give progress updates I'd like to give more
information by, for example, displaying text in a text box (eg. "Found 3
pending customer orders"), instead of simply incrementing a progress bar. Now
how can I accomplish this?

ProgressChangedEventArgs has another property: UserState. When calling the
ReportProgress method, you can use the userState parameter to pass a custom
object that contains the information that you want to display to the user.
In the ProgressChanged event handler, you can then cast the UserState to
the type of your custom object and retrieve the info.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top