2

In the last question 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);
Community
  • 1
  • 1
Priyank Bolia
  • 14,077
  • 14
  • 61
  • 82

3 Answers3

6

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
  • 295,962
  • 43
  • 465
  • 541
3

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
  • 73,706
  • 19
  • 184
  • 253
1

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
  • 30,270
  • 13
  • 89
  • 125