3

It's a very common problem every developer faces every now and then, when visual updates may be so rapid and fast that it causes the contents of the form to flicker. I'm currently using a thread to search files and trigger an event to its calling (main VCL) thread to report each and every search result. If you've ever used the FindFirst / FindNext, or done any large loop for that matter which performs very fast and rapid iterations, then you would know that updating the GUI on every little iteration is extremely heavy, and nearly defeats the purpose of a thread, because the thread then becomes dependent on how fast the GUI can update (on each and every iteration inside the thread).

What I'm doing upon every event from the thread (there could be 100 events in 1 millisecond), is simply incrementing a global integer, to count the number of iterations. Then, I am displaying that number in a label on the main form. As you can imagine, rapid updates from the thread will cause this to flicker beyond control.

So what I would like to know is how to avoid this rapid flicker in the GUI when a thread is feeding events to it faster than it's able to update?

NOTE: I am using VCL Styles, so the flicker becomes even worse.

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327

1 Answers1

4

This is indeed a common problem, not always by threads, but by any loop which needs to update the GUI, and at the same time the loop is iterating faster than the GUI is able to update. The quick and easy solution to this is to use a Timer to update your GUI. Whenever the loop triggers an update, don't immediately update the GUI. Instead, set a some global variable (like the global iteration count) for each thing which may need to be updated (the label to display the count), and then make the timer do the GUI updates. Set the timer's interval for like 100-200 msec. This way, you control the GUI updates to only occur as frequent as you set the timer interval.

Another advantage to this is the performance of your thread will no longer depend on how fast your GUI can update. The thread can trigger its event and only increment this integer, and continue with its work. Keep in mind that you still must make sure you're thread-protecting your GUI. This is an art of its own which I will not cover and assume you already know.

NOTE: The more GUI updates you need to perform, the higher you may need to tweak the timer's interval.

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
  • Not only flickering is *the issue*. Consider also, what would user have from a label which would, even if *smoothly* (without flickering), show a value that changes 100000 times per second. [+1] – TLama Jan 29 '13 at 01:10
  • Yes, that is also part of the problem which slows it down, which is why I mentioned "defeating the purpose of a thread" in the question – Jerry Dodge Jan 29 '13 at 01:17