多线程中访问public List<Entity> Entities { get { lock(syncObjecct){return ....}} set{ lock(syncObject){....}}; Entities对象时,为什么循环遍历时有时候会发生错误(Note: 我已经加锁对象并且用for循环而不是foreach循环访问对象)。
我的程序:
private List<Entity> entities = new List<Entities>();
public List<Entity> Entities { get { lock(syncObjecct){return ...entities.}} set{ lock(syncObject){....entities = value}};
private void Insert(Entity entity)
{
Entities.add(entity);
}
private void Remove()
{
if (Entityes.Count >0 )
Entities.Remove(0);
}
int main()
{
//多个线程添加删除访问Entities链表时候遍历有时会发生错误
for (int i = 0; i <Entities.Count;i++)
{
var item = Entities[0]; //报错:集合已经被修改
}
}
相关分类