x


Why does List.ToArray throw ArgumentException?

Why am I getting an argument exception telling me the destination array was not long enough while trying to make an array copy from a list?

List<MyCustomClass> asList = new List<MyCustomClass>();

// populate list etc etc.
// ...
// ...

// BANG!
// ArgumentException: Destination array was not long enough.
// Check destIndex and length, and the array's lower bounds.

MyCustomClass[] asArray = asList.ToArray();

Update:

It seems that another thread was updating the contents of the list unsynchronized so it could have been the cause of the bug. I can't tell for sure since we have since then moved on with another implementation but I am positive we had other bugs due to syncronization issues. It makes sense to think something bad can happen if the contents are changed while one thread is busy making the array. I'll hold off a couple more days until the deadline pressure release and report back if this was the sole cause in case anyone else happens to stumble across this same problem.

more ▼

asked Dec 12 '10 at 05:10 PM

Statement gravatar image

Statement ♦♦
20.1k 35 70 175

You'd be thinking there would be any arguments passed to the method to get this exception :)

Dec 12 '10 at 05:40 PM Statement ♦♦

Looks like a pretty valid error considering it's a sync issue. It'll create the array, then if you modify that array in the meantime, Array.Copy will be called with incorrect parameters and throw the exception

Dec 13 '10 at 05:22 AM Mike 3

Yeah, at the point I wrote the first comment I hadn't made clear for me that there was code running on other threads. Actually the news that we HAD several threads came as a surprise to me.

Dec 13 '10 at 05:40 PM Statement ♦♦
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You need to check your code is thread safe. Use locks or other concurrent techniques.

// asynchronous access ahead, use locks:
// one thread is doing:
lock (asList)
{
    asList.Add(new MyCustomClass());
}

// other thread is doing:
lock (asList)
{
    MyCustomClass[] asArray = asList.ToArray();
}
more ▼

answered Dec 15 '10 at 01:45 AM

Statement gravatar image

Statement ♦♦
20.1k 35 70 175

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1363
x356
x128
x32
x2

asked: Dec 12 '10 at 05:10 PM

Seen: 2401 times

Last Updated: Dec 13 '10 at 02:00 AM