问题
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