Call List <T>. Clear () that throws IndexOutOfRangeException

I have a List<T> that resides in an entity class that is populated through NHibernate. When I call .Clear() on this list, I get an IndexOutOfRangeException .

I checked that there are elements inside this list before the same exception is raised, but the same exception is thrown.

Under what circumstances do 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 off the debugger, I can query the object in the direct window and confirm that the Count () method returns 5!

+8
c # nhibernate
source share
2 answers

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

If one thread deletes an item when the list is cleared by another thread, this exception may be thrown.

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

+7
source share

If you use streams, block the call to the Clear() method.

 private readonly object obj = new Object(); private readonly List<VacancyTag> _vacancyTags = new List<VacancyTag>(); public virtual void RemoveAllVacancyTags() { lock(obj) { _vacancyTags.Clear(); } } 
0
source share

All Articles