Search code examples
delphilist-manipulation

How to exchange TList items during a for-loop


I have a TList which' items are continuously processed by many for-loops. I sometimes need to exchange items in the list in order to rearrange the order of the visual representation of the list (in a StringGrid).

How do I exchange these items?

My preliminary thoughts are:

  • During the for-loop I think the items should not be exchanged.
  • If I do the exchange in a Timers' OnTimer event, having set the Timers' interval to a very short interval (e.g. 1 millisecond), then I think the for-loop will have only an intermission of that one millisecond.

Will this work? Or are there better alternatives?


Solution

  • As long as you ensure that the count of the items in a TList does not change, exchanging items is perfectly fine during a for-loop. Note that, depending on the index of the items that are about to be exchanged, some of the items may not be processed or may be processed twice.

    If the exchange operation is not called from within the for-loop, then an already started for-loop will run until it is done. You cannot expect to "break in" with a Timer, because that Timer's message will not be processed until the for-loop and all surrounding code is done.

    So, the solution for your problem could be:

    • exchange the items within the for-loop,
    • use a threading solution to be able to do two different things simultaniously on one list (this may need some learning about threads),
    • wait until the for-loop is done, and exchange then,
    • split the for-loop in multiple slices to reduce the time needed, or
    • use a timer to start multiple for-loops in order to give your program some breathing time in between.