积极答复者
请问多线程List<T>操作的问题

问题
答案
-
foreach内部用的是List.Iterator,当List的内容改变时,Iterator会立即失效,再次访问iterator就会抛异常。
你可以考虑把foreach改成for (int i = 0; i < T1.Count; ++i),这样应该就没问题了。
Shuhai Shen - I love programming, travel and photographing. Welcome to my blog: http://leonax.net- 已建议为答案 络绎 2010年8月20日 13:15
- 已标记为答案 BoberSongModerator 2010年8月26日 5:40
-
两个知识点,
首先,foreach (对枚举器的包装)过程是不能增加或者删除集合即不能出现这样的代码 foreach(T item in oneList<T>) { oneList<T>.Remove(item); }
其次,多线程,显然你需要考虑线程同步。对 List<T> 进行从头到尾枚举过程不是线程安全的,像你这种读与写竞争的情况,最简单的实现是在整个枚举期间锁定集合,比如
// 读线程
lock(theList<T>) {
foreach(T item in oneList<T>) { // read each item}
}
// 写线程
lock(theList<T>) {
oneList<T>.Add(obj);
}此外,使用 for 或者 while 只能解决问题1,线程同步依然需要考虑
问题要简单,错误须详细@错误/异常/堆栈信息+操作系统+软件版本+all the context of the issue Hope Helpful | http://www.leoworks.net
- 已标记为答案 BoberSongModerator 2010年8月26日 5:41
全部回复
-
foreach内部用的是List.Iterator,当List的内容改变时,Iterator会立即失效,再次访问iterator就会抛异常。
你可以考虑把foreach改成for (int i = 0; i < T1.Count; ++i),这样应该就没问题了。
Shuhai Shen - I love programming, travel and photographing. Welcome to my blog: http://leonax.net- 已建议为答案 络绎 2010年8月20日 13:15
- 已标记为答案 BoberSongModerator 2010年8月26日 5:40
-
两个知识点,
首先,foreach (对枚举器的包装)过程是不能增加或者删除集合即不能出现这样的代码 foreach(T item in oneList<T>) { oneList<T>.Remove(item); }
其次,多线程,显然你需要考虑线程同步。对 List<T> 进行从头到尾枚举过程不是线程安全的,像你这种读与写竞争的情况,最简单的实现是在整个枚举期间锁定集合,比如
// 读线程
lock(theList<T>) {
foreach(T item in oneList<T>) { // read each item}
}
// 写线程
lock(theList<T>) {
oneList<T>.Add(obj);
}此外,使用 for 或者 while 只能解决问题1,线程同步依然需要考虑
问题要简单,错误须详细@错误/异常/堆栈信息+操作系统+软件版本+all the context of the issue Hope Helpful | http://www.leoworks.net
- 已标记为答案 BoberSongModerator 2010年8月26日 5:41
-