Exception: System.ArgumentException: The length of the destination array is not sufficient. Please check the Destindex and length and the lower bounds of the array. (Sorry to forget it)
The code for the exception that occurred is as follows:
var New List<topic>(); Parallel.For (21, page == {//AddRange method exception occurred List. AddRange (gettopics (board. (Boardid, page));});
cause the:list<t> collection is not thread-safe, and internal computations can cause problems when the List is concurrently manipulated. (Specific internal what will happen, I this rookie here will not show off, you can decompile to see the List of internal implementation principle)
After searching on the StackOverflow, there are 2 solutions: the original answer
Address: http://stackoverflow.com/questions/8796506/ Correct-way-to-guarantee-thread-safety-when-adding-to-a-list-using-parallel-libr
That is: the first, using lock plus locks
Private Static ReadOnly Object New Object (); Parallel.For (21, page == {vargettopics (board). Boardid, page); Lock (Locker) { list. AddRange (range); }});
Second, use AsParallel (). SelectMany and took place into a Enumerable
// generates an integer sequence var nums = Enumerable.range (21); // use AsParallel to perform concurrent operations, and use SelectMany to map each element to a new object and then merge the results into a single collection var range = Nums. AsParallel (). SelectMany (page = gettopics (board. Boardid, page)); // the synchronization is added to the list list. AddRange (range);
After looking up on MSDN, we found that there is a namespace implementation of some thread-safe collection classes, such as
Address: Https://msdn.microsoft.com/zh-cn/library/system.collections.concurrent (v=vs.100). aspx
The above thread-safe collection Class I have not used, but since it is provided by Microsoft, presumably the performance of all aspects should be good, we can choose according to the applicable scenario.
Small note: The length of the destination array is not sufficient. Please check the Destindex and length and the lower bounds of the array.