Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Destination array is not long enough to copy all the items in the collection.

I have a Dictionary<string, mystruct> instance, for which I am grabbing a list of all values:

var list = m_Records.Values.ToList();

I occassionally get the following error:

ArgumentException
Destination array is not long enough to copy all the items in the collection. Check array index and length.

I'm trying to figure out how that is even possible from that one very basic line. When VS2010 breaks on that error, I can inspect m_Records and see it has, say, 24 entries (varies a bit). But it does have values, and m_Records is certainly not null.

like image 865
CoolUserName Avatar asked Jan 23 '12 20:01

CoolUserName


3 Answers

Are you by chance modifying the dictionary on another thread while calling ToList? That will cause this error, and only occasionally, as you say, as such issues depend on thread timing issues which are notoriously persnickety. I can't think of any other reason this would happen.

Instead, you should be using ConcurrentDictionary (or, stop multi-threading). (Doc, it hurts when I do this. Then don't do that.)

like image 182
jason Avatar answered Sep 21 '22 18:09

jason


If this is just LINQ to Objects, I strongly suspect that you're accessing the dictionary from a different thread at the same time. I'd be very surprised to see it fail otherwise. (ToList isn't particularly complicated to implement - I doubt that the BCL team messed this one up.)

Dictionary<TKey, TValue> is not thread-safe if any threads are modifying it. If you need one which is, you should look at ConcurrentDictionary<TKey, TValue> in .NET 4.

Otherwise, just make sure you only access the dictionary (for read or write) in one thread at a time.

like image 38
Jon Skeet Avatar answered Sep 18 '22 18:09

Jon Skeet


This error shows up if something is modifying your Dictionary while you're reading it. Dictionaries aren't thread safe for writing, if you need them to be you should use ConcurrentDictionary.

like image 36
Joachim Isaksson Avatar answered Sep 17 '22 18:09

Joachim Isaksson