BackgroundWorker still needs to call Invoke?

[亡魂溺海] 提交于 2019-12-01 08:27:38

问题


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);

回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1968222/backgroundworker-still-needs-to-call-invoke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!