views:

343

answers:

3

In the last question http://stackoverflow.com/questions/1952201/display-progress-bar-while-doing-some-work-in-c, people has recommend use of BackgroundWorker. I thought in BackgroundWorker DoWork method you can update the GUI directly, but why this function call need to be called using Invoke.

toolTip.SetToolTip(button, toolTipText);
+2  A: 

You are mistaken, you can't call the UI thread directly from the handler for the DoWork method, as this is on the background thread.

If you want to update the UI, you should call the ReportProgress method and then update the UI from the event handler for the ProgressChanged event.

While you can call the Invoke method in the background thread, doing so defeats the purpose of using the BackgroundWorker class. The ProgressChanged event is thrown on the UI thread and is the mechanism you should use to update the UI components when something changes on the background thread.

casperOne
+1. from me.......
Mitch Wheat
+5  A: 

The RunWorkerCompleted callback is marshalled onto the UI thread; DoWork is not.

You should use the ReportProgress method to update the UI during DoWork processing.

See: How to: Run an Operation in the Background

Mitch Wheat
+1  A: 

Keep in mind that if you call RunWorkerAsync() from non UI thread you will need to call Invoke from the ProgressChanged and RunWorkerCompleted event handlers.

Giorgi