Calling List<T>.Clear() causing IndexOutOfRangeException

强颜欢笑 提交于 2020-01-30 04:28:12

问题


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();
}

Edit:

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!


回答1:


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.

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




回答2:


If you're using threads, please lock the call of the method Clear().

private readonly object obj = new Object();

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

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


来源:https://stackoverflow.com/questions/9393371/calling-listt-clear-causing-indexoutofrangeexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!