I have a List that is cleared out every so often. The code is exactly like this:
VisitorAgent[] toPersist;
List<VisitorAgent> v = (List<VisitorAgent>)state;
lock (v)
{
toPersist = v.ToArray();
v.Clear();
}
//further processing of toPersist objects
Today i just got an Argument exception which doesn’t make sense to me unless there was a memory issue. But if that was the case, why not OOM exception? What could cause this exception when calling ToArray()?
System.ArgumentException: Destination array was not long enough. Check destIndex and
length, and the array's lower bounds.
I am using .NET 3.5 & C#.
This just screams race condition (the
lockstatement was the first clue).I’d guess that some other code (in another thread) has added to the
List<T>after it allocates the destination array but before it gets around to copying it.The first thing I’d do is double-check that every possible access to your state list is properly wrapped in a
lockstatement.