我有一个使用 BackgroundWorker 处理 IEnumerator<T> list
的小应用程序在任何时候。
代码基本上是这样的:
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);
}
现在我有一个按钮和一个文本框,它们将直接添加到 IEnumerator。
问题是,在我添加按钮后,后台工作人员继续处理它当前正在处理的项目,但会在完成该项目后停止。它不会继续。
如何在不影响后台工作人员的情况下安全地将项目添加到列表中?除了后台工作人员之外,还向项目添加对象。解决方案应该是什么?
谢谢
最佳答案
让后台工作人员迭代原始列表的副本,而不是列表本身。
while (true)
{
foreach (T item in new List<T>( list ))
{
....
}
Thread.Sleep(500);
}
如果您尝试在枚举集合时修改集合,枚举器将抛出异常。来自docs :
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current returns the element that it is set to, even if the enumerator is already invalidated.
关于c# - 如何在迭代时将 ListItem 添加到列表中 (C#)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372125/