Winforms Update Ui From Backgroundworker Progresschanged
- Winform Update Ui
- Android Update Ui From Thread
- Winforms Update Ui From Backgroundworker Progresschanged
Guide to using BackgroundWorker in C#. You have some complex calculation or maybe you're connecting to a slow server from your application and it blocks the UI thread. However, the background worker is not ideal if you need constant communication between the two threads. BackgroundWorker Component in WPF An overview of the BackgroundWorker component by JeremyBytes.com. Point, we can update our UI and do clean up (if required). So, let’s put our process into the background. I am updating a label text on a backgroundworker progressChanged event (literally one 1 line of code in this event callback). Its updating about 50 times in around 45 seconds and the issue is that the UI only seems to update about 10 times.
I've been searching and found that a good way to perform background work and update the GUI is using background workers. However, doing this (stupid) little task (counting from 1 to 10000) it doesn't update the label content but prints to the debug! (This is just a spike solution for another project of course..)
Here's the code:
Miguel RibeiroWinform Update Ui
Miguel Ribeiro3 Answers
The ProgressChanged
event is raised on the UI thread, not the worker thread. In your code, the worker thread is doing almost nothing (just loop from 0 to 10000 and call ReportProgress
), most of the work is done on the UI thread. Basically, you're sending too many progress notifications. Because of this, the UI thread is almost always busy and has no time to render the new content of the label.
Rendering in WPF is not performed immediately when you change a property of a control, it is done on a separate dispatcher frame, which is processed when the dispatcher has nothing more urgent to do, based on the priority of the task. The priority used for rendering has a value of 7 (DispatcherPriority.Render
); the ProgressChanged
event is marshalled to the UI thread with a priority of 9 (DispatcherPriority.Normal
), as specified on MSDN. So the ProgressChanged
notifications always have a higher priority than rendering, and since they keep coming, the dispatcher never has time to process the rendering tasks.
If you just decrease the frequency of the notifications, your app should work fine (currently you're sending 100 notifications for each percentage value, which is useless):
Thomas LevesqueThomas LevesqueTry to change the label using womething like this:
Note that i'm not sure it will work. I can not test it now. If it does not work, let me know and I will delete the answer.
If you need the a canonical way to do exactly what you want, look at the Hath answer in this post: How do I update the GUI from another thread?
keepAlive