tags:

views:

25

answers:

2

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#.

+5  A: 

This just screams race condition (the lock statement 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 lock statement.

Ben M
Im almost positive you are right, after you said that, i went through all my refences to the state object, and it looks like i missed one.
Mike_G
A: 

Something is changing the state list between the time the array is allocated and the time the contents of the list are copied. Locking on v would have no effect on this unless the code that populates state knows about v (which it doesn't seem to in this example).

Ben Hoffstein