deleting keypair from hashtable while enumerating !??!

  • Thread starter Thread starter Tony
  • Start date Start date
T

Tony

I have this problem - I have a hashtable, containing a list of filenames.

Every 60 seconds, I have a thread that enumerates thru this hashtable, and
based on some simple logic, some of the items in the hashtable has to be
removed.

But when I remove a pair from the hashtable, inside the enumeration loop, I
get an exception.

Why cant I remove from a hashtable, while enumerating ?

My code looks something like this :

for each r in camImages
if r.value = x then
camImages.remove(r.key)
end if
next

When the above code is running, the first time the "camImages.remove(r.key)"
line is run, I get an exception in the last line, containing "next".

Can someone explain to me what I am doing wrong ?


-
Regards,
Tony Fonager

Netcoders ApS
 
Tony,
Why cant I remove from a hashtable, while enumerating ?
Because the enumerator (an object that implements IEnumerator, an interface
used by For Each) may 'loose' track of where it is if you delete an item,
the element the enumerator is on is no longer in the collection, so when it
goes to get the next element it has no idea where to look, as the internal
structure of the HashTable has changed. Yea, Yea, The HashTable & enumerator
could let each other know when this happens, but the 'expense' of doing this
is greater then the 'benefit'.

Generally the way to delete items while enumerating is to make a copy of the
Keys collection, then enumerator of this copy, or to add the items you want
deleted to a second collection (ArrayList for example). then delete based on
the items in this second collection. I tend to go for the second.

To make a copy of the Keys collection see Hashtable.Keys.CopyTo.

Hope this helps
Jay
 
Jay,

Thanks for your reply and suggestions - I thought of doing it the same way
as you suggest, with a copy of the keys.

But before that, I just had to know if I was doing something wrong ;-)

-
Regards,
Tony Fonager
 
Back
Top