Question

How is it possible to pass a dictionary as a parameter to a thread function and then iterate through it?

Dictionary<string, Track> dic = allTracks;
updateThread = new Thread(() => toDB(dic));
updateThread.Start();

and the function:

public static void  toDB( Dictionary<string, Track>  dict)
   {
        foreach (KeyValuePair<string, Track> pair in dict)
        { 
          //do something - but I do not alter anything in dictionary 
        }
   }

I have tried like this but I get an error

Collection was modified; enumeration operation may not execute.

Was it helpful?

Solution

You will get this exception if your dictionary is modified in the main thread or the thread you have passed on to. You can use ConcurrentDictionary or implement the locking yourself.

However, if you do not intend to modify the original collection inside the function you are calling in the thread and you don't need the latest values either, then you can simple create a copy before passing it to your seperate thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top