迭代时从另一个线程修改列表(C#) [英] Modifying list from another thread while iterating (C#)
本文介绍了迭代时从另一个线程修改列表(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用foreach遍历元素列表,像这样:
I'm looping through a List of elements with foreach, like this:
foreach (Type name in aList) {
name.doSomething();
}
但是,在另一个线程中,我正在调用类似的东西
However, in an another thread I am calling something like
aList.Remove(Element);
在运行时,这将导致InvalidOperationException:集合已被修改;枚举操作可能无法执行.最好的处理方法是什么(即使以性能为代价,我也认为它很简单)?
During runtime, this causes an InvalidOperationException: Collection was modified; enumeration operation may not execute. What is the best way to handle this (I would perfer it to be rather simple even at the cost of performance)?
谢谢!
推荐答案
线程A:
lock (aList) {
foreach (Type name in aList) {
name.doSomething();
}
}
线程B:
lock (aList) {
aList.Remove(Element);
}
这当然对性能不利.
这篇关于迭代时从另一个线程修改列表(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文