go though Hashtable.Values thread saft?

  • Thread starter Thread starter Ryan Liu
  • Start date Start date
R

Ryan Liu

Hashtable.GetEnumerator is not thread safe, but what about I write I loop go
though Hashtable.Values, is that thread saft?

Thanks a lot!
 
Hi Ryan,
enumerating through a Collection is not a thread-safe operation, as you
mentioned. Even if you try to iterate through the values collection it is
possible another thread will alter the collection while you are trying to
iterate through them.

You can use the SyncRoot property which most collections provide to use as
a lock so that only one thread can be accessing the collection at any one
time i.e.

Hashtable myHashtable = new Hashtable();

lock(myHashtable.SyncRoot)
{
//iterate through the hashtable
}

You need to also lock in the method where you are modifying the hashtable.

Hope that helps
Mark R Dawson
 

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

Back
Top