BackgroundWorker still needs to call Invoke?

后端 未结 3 390
面向向阳花
面向向阳花 2021-01-15 08:00

In the last question Display progress bar while doing some work in C#?, people has recommend use of BackgroundWorker. I thought in BackgroundWorker

相关标签:
3条回答
  • 2021-01-15 08:20

    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

    0 讨论(0)
  • 2021-01-15 08:30

    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.

    0 讨论(0)
  • 2021-01-15 08:39

    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.

    0 讨论(0)
提交回复
热议问题