0

I have a string list List<string> mylist.I have a background operation that adds strings to this list. i use another background operation to process the strings in this list

foreach (string pfile in mylist) 
{
//dostuff
}

This results in this exception

Collection was modified; enumeration operation may not execute

I cannot fetch the full list of files before hitting the loop as a timer operation adds files to the list while the loop is running.How can i get around this problem.Please advice.

techno
  • 6,100
  • 16
  • 86
  • 192

1 Answers1

0

You have to institute some kind of locking.

private object _locker = new object();  // Class member object

void ProcessList()  // Or whatever it's called
{
    lock (_locker)
    {
        foreach (string pfile in mylist)
        {
            //dostuff
        }
    }
}

Make sure you wrap the other thread's add activity in a lock also, using the same _locker object.

If the //dostuff code takes a long time, you might want to consider operating on a copy of the list to minimize the amount of time the list is locked:

    string[] mylistCopy;

    lock (_locker)
    {
        mylistCopy = mylist.ToArray();
    }

    foreach (string pfile in mylistCopy)
    {
        //dostuff
    }
itsme86
  • 19,266
  • 4
  • 41
  • 57