Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling List<T>.Clear() causing 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();
}

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!

like image 441
starskythehutch Avatar asked Feb 22 '12 10:02

starskythehutch


1 Answers

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.

like image 56
ken2k Avatar answered Oct 24 '22 22:10

ken2k