This question is about keeping the GUI responsive during longer-running tasks (a few seconds in most cases).
I extensively use threads and a task pattern to execute expensive task in a background thread. But what about GUI updates that takes some time? For example, filling a large string grid or tree view? A thread does not help here because everything needs to be synchronized with the main thread anyway.
I know the problems of Application.ProcessMessages
, but currently it seems like the only solution to put calls to ProcessMessages
inside the GUI update methods.
Any better ideas?
IMO if the GUI update is the bottleneck (even if BeginUpdate/EndUpdate is used as @The_Fox suggests) then it is time to reconsider the GUI controls used. The standart grids, treeviews, listboxes aren't simply cut for handling very large number of items. There are many performant thirdparty controls both free and commercial for that purpose.
For a starter, check out VirtualTreeview if the bottleneck is in a grid, treeview or a listbox context.
When filling Grids, Lists, DataSets etc., call BeginUpdate/EndUpdate DisableControls/EnableControls. This will save you time. I also had a thread that did some calculations, but nevertheless the GUI was slow, until I called DisableControls on the datasets that were being modified and not visible because the controls are on another tabsheet.
Also, when updating controls, have all the data you need prepared, so you can just fill your list, without doing calculations that can slow this down.
What's wrong with Application.ProcessMessages in your case? The Application.ProcessMessages method is exactly for such cases. The problem with Application.ProcessMessages is the code like this:
repeat
Application.ProcessMessages;
until SomethingHappens;
That is bad since it is useless CPU load, and should be replaced by
repeat
Application.HandleMessage;
until SomethingHappens;
which yields processor time to other threads. Single Application.ProcessMessages calls (not in loop) are OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With