BackgroundWorker.ProgressChanged Event

  • Thread starter Thread starter Guest
  • Start date Start date
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.
 
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
 
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.
 
Back
Top