views:

75

answers:

3

I have seen others with a similar issue but not quite what I was looking for. In the backgrounderworker class dowork event I create an instance of a new class and call one of it's function. Previously, I had this code in a windows.form.timer tick event and would pass a delegate in as one of the parameters which would allow the function and other functions it calls within the class to call a method on the form to update a datagrid on the GUI. Is there a way to do this within the dowork event? I need this because the function I call from dowork calls other functions and I want each of those functions to log information in the GUI datagrid.

A: 

Apart from ReportProgess mentioned in Hans' answer, you can alternatively use Control.Invoke on one of the UI elements to exeute code in the UI thread.

Heinzi
But in DoWork, can I pass this ability (as a delegate parameter) to a class I instanstiate in DoWork?
@user94593: Sure.
Heinzi
do you happen to have a code example?
@user94593: Control.Invoke's MSDN page (see the link in my answer) contains an example at the end.
Heinzi
@user94593: The second overload, which allows you to pass parameters, might be interesting for you as well (again, example is included at the bottom): http://msdn.microsoft.com/en-us/library/a1hetckb.aspx
Heinzi
+4  A: 

The BackgroundWorker.ReportProgress() method was intended to do that. You implement the ProgressChanged event to update the UI, it will run on the main thread. You're not restricted to report just a progress percentage, you can pass any object as well to pass info to the event handler by using the overload that accepts the userState argument. Beware that you have to use proper locking if you do that.

Hans Passant
Don't forget to set the `WorkerReportsProgress` property to `true` on the background worker itself.
Scott Anderson
Here is the issue I am having with using ReportProgress. In DoWork, I make a call to a function. That function makes calls to other functions. I want all those functions to be able to send status updates to the UI.
So, write a function that calls ReportProgress so that all these other functions can call it. Pass a delegate if you have to. Be careful, the thread marshaling is very expensive. Call it more than ~1000 times per second and the UI thread goes dead when it can't keep up anymore.
Hans Passant
A: 

You can send progress data back to the UI thread, you will get an event for that on the UI thread, then you can update the screen. It is highly preferred that the objects you send back to the UI thread are immutable. Besides calling the ReportProgress and handling the event you need to opt-in by setting WorkerSupportsProgress property to true.

jdv