BackgroundWorker still needs to call Invoke?
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.Set开发者_开发技巧ToolTip(button, toolTipText);
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
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.
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.
精彩评论