I have a small application that using BackgroundWorker to process the IEnumerator<T> list at all time.
The code basically like this:
while(true){
foreach(T item in list){
// Process each item and send process
// Add an object in child List ( List<T1> item.Result )
}
Thread.Sleep(500);
}
Now I have a button and a textbox, which will add directly to the IEnumerator.
The problem is that after I add button, the backgroundworker continue to process it’s currently processing Item, but will stop after finish that item. It does not continue.
How can I safely add an Item to the list without affect the backgroundworker? Beside the background worker also do adding objects to the item. What should be the solution for this?
Thank you
Have the background worker iterate over a copy of the original list, not the list itself.
If you attempt to modify a collection while enumerating over it, the enumerator will throw an exception. From the docs: