开发者

ArgumentException when calling .ToArray()

开发者 https://www.devze.com 2023-01-06 02:21 出处:网络
I have a List that is cleared out every so often.The code is exactly like this: VisitorAgent[] toPersist;

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消