Best practice to modify list during iteration

M

MM

Hi, I'm writing a scheduling class. On each clock tick, I scan the
trigger list to see which if any triggers have been activated. If so,
execute the callback and if it is a periodic trigger to reinsert it in
the list at some future time. So it's a matter of removing and possibly
adding the trigger within the same function. I don't that you can modify
the list while enumerating it - ie: psuedocode

foreach (trigger in triggers)
{
if (reachedtime)
deleteit
if (trigger is Periodic)
reinsert in list)
}

so I scan the list, find the active triggers, use triggers.GetRange() to
create a new ActiceTriggers list and enumerate that instead and then
modify the *real* triggers list without worrying about modifying it
within an iteration. OK, all this works fine. The question is, what's
best practice for this sort of activity as there'a quite an overhead for
creating a new TriggerList object on each clock tick. Is it possible to
modify a list while iterating over it safely. Thanks for you guidedance.
Matt.
 
A

Arne Vajhøj

Hi, I'm writing a scheduling class. On each clock tick, I scan the
trigger list to see which if any triggers have been activated. If so,
execute the callback and if it is a periodic trigger to reinsert it in
the list at some future time. So it's a matter of removing and possibly
adding the trigger within the same function. I don't that you can modify
the list while enumerating it - ie: psuedocode

foreach (trigger in triggers)
{
if (reachedtime)
deleteit
if (trigger is Periodic)
reinsert in list)
}

so I scan the list, find the active triggers, use triggers.GetRange() to
create a new ActiceTriggers list and enumerate that instead and then
modify the *real* triggers list without worrying about modifying it
within an iteration. OK, all this works fine. The question is, what's
best practice for this sort of activity as there'a quite an overhead for
creating a new TriggerList object on each clock tick. Is it possible to
modify a list while iterating over it safely. Thanks for you guidedance.

I would create a new list and move those to be kept over in
the new list.

It will give the cleanest code and most likely the fastest code
(because deleting from an array backed list is a very expensive
operation).

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top