deleting keypair from hashtable while enumerating !??!

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
 
J

Jay B. Harlow [MVP - Outlook]

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
 
T

Tony

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
 

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