问题描述:

I received an error when creating one thread to add to listbox from one list

here is code

private void textBoxSearch_TextChanged(object sender, EventArgs e)

{

listBoxSuggest.Items.Clear();

{

string temp = ((TextBox)sender).Text;

mythread = new Thread(()=> UpdateListBox(temp) );

mythread.Start();

}

}

private void UpdateListBox(string queyt)

{

if (queyt !=null)

{

if (myPrefixTree.Find(queyt))

{

var match = myPrefixTree.GetMatches(queyt);

foreach (string item in match)

this.Invoke((MethodInvoker)(() => listBoxSuggest.Items.Add(item)));

}

}

}

I received an error

Collection was modified; enumeration operation may not execute.

I need a solution to problem...

update...

While running the program, I received an error in

 foreach (string item in match)

网友答案:

The problem is that you called something, such as .Add or .Remove, which edits the content of your enumeration while it was being iterated over. this causes the iteration to fail, because now it's not sure whether to proceed with the new element (which may have an index set before the current index) or skip the old element (which may have already been processed or may even be the current item).

You need to make sure that any loop which may modify contents of the loop it's calling over instead iterates over a copy of that enumeration. ToArray and ToList can both server this purpose -

foreach(var item in collection.ToArray()) ...

- or -

foreach(var item in collection.ToList()) ...

This means that when something inevitably calls collection.Add somewhere within the body of your loop, it modifies the original collection, not the one being iterated, and thus preventing errors. It can, however, mean that it will process over something that was removed earlier in the iteration, in which case you may need a more complicated soltion.

相关阅读:
Top