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