Note: The length of the target array is insufficient. Check the destIndex, length, and lower limit of the array ., Note destindex
Exception: System. ArgumentException: the length of the target array is insufficient. Check the destIndex, length, and lower limit of the array. (Sorry, I forgot)
The error code is as follows:
Var list = new List <Topic> (); Parallel. for (2, totalPage + 1, page => {// The AddRange method has an exception list. addRange (GetTopics (board. boardID, page ));});
Cause: the List <T> set is not thread-safe. Internal computation may fail During Concurrent List operations.(What problems will occur inside the system? I won't sell this cainiao here. You can decompile it to see the internal implementation principles of the List)
Two solutions are available on StackOverflow:
Address: http://stackoverflow.com/questions/8796506/correct-way-to-guarantee-thread-safety-when-adding-to-a-list-using-parallel-libr
That is: first, use lock to lock
private static readonly object locker = new object();Parallel.For(2, totalPage + 1, page =>{ var range = GetTopics(board.BoardID, page); lock(locker) { list.AddRange(range); }});
Second, use AsParallel (). SelectMany and generate an Enumerable
// Generate an integer sequence var nums = Enumerable. range (2, totalPage-1); // execute concurrent operations using AsParallel, map each element to a new object using selectpage, and combine the results into a set var range = nums. asParallel (). selecttopics (page => GetTopics (board. boardID, page); // synchronously add to List. addRange (range );
After searching on MSDN, it is found that some thread security collection classes are implemented in a namespace, such
Address: https://msdn.microsoft.com/zh-cn/library/system.collections.concurrent (v = vs.100). aspx
I haven't used these thread-safe collection classes for the time being. However, since they are provided by Microsoft, we must have good performance in all aspects. You can choose one based on the applicable scenarios.