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.
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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With