调用List< T> .Clear()导致IndexOutOfRangeException [英] Calling List<T>.Clear() causing IndexOutOfRangeException

查看:63
本文介绍了调用List< T> .Clear()导致IndexOutOfRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List< T> ,它位于通过NHibernate填充的实体类中.当我在该列表上调用 .Clear()时,我得到的是 IndexOutOfRangeException .

I have a List<T> that is in an entity class that is being populated via NHibernate. When I call .Clear() on that list, I am getting an IndexOutOfRangeException.

我已经验证了该列表在调用此列表之前已经包含了项,但是抛出了相同的异常.

I've verified that that list has items in in before this is called, but the same exception is thrown.

在什么情况下调用此方法时,您希望得到此异常?

Under what circumstances would you expect to get this exception when you call this method?

private readonly List<VacancyTag> _vacancyTags = new List<VacancyTag>();

public virtual void RemoveAllVacancyTags()
{
    _vacancyTags.Clear();
}

疯狂的事情是,即使在引发异常并中断调试器之后,我也可以在立即窗口中查询对象,并可以确认Count()方法返回的值是5!

The crazy thing is that even after the exception is thrown and I break the debugger, I can query the object in the immediate window and can confirm that the Count() method is returning the value 5!

推荐答案

典型的情况是,当有多个线程访问同一列表时.

A typical case is when you have multiple threads accessing the same list.

如果一个线程在另一个线程清除列表时删除了一个项目,则可能引发此异常.

If one thread deletes an item while the list is being cleared by another thread, this exception could be thrown.

请记住,不是线程安全的 List< T> 类.

Remember the List<T> class is not thread-safe.

这篇关于调用List&lt; T&gt; .Clear()导致IndexOutOfRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆