Collection was modified while enumeration
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Collection was modified; enumeration operation may not execute
我有一个通用列表,在其中枚举时执行一些操作。
1 2 3 4 5 6 | foreach(Action<string> action in actionList) { if(action != null) { action(mystring); } } |
现在我得到这个例外:
1 2 | InvalidOperationException: Collection was modified; enumeration operation may not execute |
如何解决这个问题?我被紧紧地钉在.NET 3.5上:/
好presumably one of the actions modifies
1 2 3 4 5 6 | foreach(Action<string> action in actionList.ToList()) { if(action != null) { action(mystring); } } |
或是:P></
1 2 3 4 | foreach (var action in actionList.Where(action => action != null).ToList()) { action(mystring); } |
你在网上actionlist修饰the the迭代它。它是在第二个线程which is not with a synchronized method which the action or电流回路改造or another make the迭代。我的解决方案是:theP></
1 2 3 4 5 6 7 | var tmp = new List<Action<string> >(actionList); foreach(Action<string> action in tmp) { if(action != null) { action(mystring); } } |
但它只会工作在房屋的房屋action' modification of You should并行线程在synchronize of the list。P></