调用.ToArray当ArgumentException的()ToArray、ArgumentException

2023-09-06 08:17:39 作者:一分心动

我有被清除出每隔一段时间列表。在code是完全一样的:

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

今天,我刚刚得到一个参数异常这是没有道理的,我必须有一个内存问题。但是,如果是这样的话,为什么不OOM异常?调用的ToArray()时,这是什么原因异常?

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.

我使用.NET 3.5安培; C#。

I am using .NET 3.5 & C#.

推荐答案

这只是尖叫比赛条件(锁定语句是第一条线索)。

This just screams race condition (the lock statement was the first clue).

我猜想,一些其他的code(在另一个线程)添加到名单,其中,T&GT; 后,分配目标阵列,但它得到前各地要复制它。

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.