LINQ: The destination array is not long enough to copy all the elements in the collection.

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

 var list = m_Records.Values.ToList(); 

Sometimes I 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 am trying to understand how this is possible even from one very simple line. When VS2010 breaks down on this error, I can check m_Records and see that it has, say, 24 records (varies slightly). But it does matter, and m_Records, of course, is not null.

+4
source share
3 answers

Do you accidentally modify a dictionary in another thread by calling ToList ? This will cause this error, and only occasionally, as you say, since such problems depend on thread synchronization problems, which are known to be widespread. I can’t think of any other reason that this will happen.

Instead, you should use ConcurrentDictionary (or stop multithreading). (Doc, it hurts me when I do this. Then don't do this.)

+11
source

If this is only LINQ to Objects, I strongly suspect that you are accessing a dictionary from another thread at the same time. I would be very surprised to see that this would not work otherwise. ( ToList not particularly difficult to implement - I doubt the BCL team messed that up.)

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

Otherwise, just make sure that you only open the dictionary (for reading or writing) in one thread at a time.

+6
source

This error appears if something changes your dictionary while reading it. Dictionaries are not thread safe for writing; if you need them, you should use ConcurrentDictionary.

+1
source

Source: https://habr.com/ru/post/1392544/


All Articles