- Home /
Lists: Avoiding ArgumentOutOfRangeException: Argument is out of range errors
Hi,
I'm trying to expand my knowledge of Lists and I've been experimenting the last few days. My current focus is on avoiding ArgumentOutOfRangeException: Argument is out of range errors when other functions or scripts are accessing a List that is constantly being updated.
Even checking if an element in a List is actually there before doing something can still result in these errors, so I am guessing between checking and doing, the List has changed.
My next focus of attention is here: http://msdn.microsoft.com/en-us/library/3azh197k%28v=vs.110%29.aspx
Am I on the right track or does anyone have some solid advice on how best to avoid out of index scenarios?
Thanks!
Answer by Traiger · Jan 05, 2014 at 12:30 PM
using ForEach is a good way of avoiding the outofRangeExceptions as you are not responsible for maintaining an item count. For example:-
var myList = new List<int>();
foreach(var item in myList)
{
Debug.Log (item);
}
Hi Traiger,
I have tried that approached and still get errors. For example I have a list that contains a groups of ints that is being modified all the time. The following still gives me out of index errors when the rate of changes gets pretty quick (about every .5 seconds or faster will make it fall over):
for(var group in intGroups)
{
countTotal = group.recordedNumbers.Count;
}
Actually looking at it closer this seems to work better:
for(var group in intGroups)
{
if(group.recordedNumbers)
{
countTotal = group.recordedNumbers.Count;
}
}
Will investigate further, and update :)
Are you modifying the list on a timer and then trying to do something with the list in a different thread?
Perhaps this is a threading issue, http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx may help.
I have various functions in the same script running as While(true) which update the list. It does very much feel like a ti$$anonymous$$g issue of some kind. Will investigate this also and update.
That said the previous code I posted seem to have stopped all errors when reading from a List.
Well it seemed to help so I'll mark this as answered :) Thanks Traiger.