Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Threadin issue

Status
Not open for further replies.

s2001

Programmer
Dec 7, 2001
132
US
Hello All,

I am having problem sharing information between two threads.

-- Thread 1 -- Reads value (calls ReadVal) from the Hashtable.
-- Thread 2 -- Adds value (calls Add) to the Hashtable.

What is happening is when i read the value, i get the exception :

Collection was modified; enumeration operation may not execute.

Any help would be greatly appreciated.

Code:
Class Hashes:

public static string ReadVal()
        {
            string str = string.Empty; 
            //lock (locker)
            //{
               
                
                IDictionaryEnumerator en = t.GetEnumerator();
                //***Get the error here. ****
                while (en.MoveNext())
                {
                    str = en.Value.ToString();
                    t.Remove(en.Key);
                }
            //}
            return str;
        }

        public static void Add(int val)
        {
            lock (locker)
            {
                try
                {
                    t.Add("Hello:" + val, val);
                }
                catch (Exception)
                {
                    int num = rc.Next();
                    t.Add("Hello:" + num, val);
                }
            }
        }



Thanks,
Murali Bala
 
You can't modify a collection (hashtable, list, dictionary, etc) while in the middle of a loop.

Thread 1 must lock the hashtable for use exclusively and Thread 2 can add to the list when it's done.

do some googling for C# Lock

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top