首页 > 编程语言 >C# Parallel foreach Parallel Source array was not long enough. Check srcIndex and length, Destinatio

C# Parallel foreach Parallel Source array was not long enough. Check srcIndex and length, Destinatio

时间:2024-06-05 11:12:30浏览次数:23  
标签:set get modelBList System long length using array public

//Index was outside the bounds of the array.

//Source array was not long enough. Check srcIndex and length, and the array's lower bounds
//
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp135 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); ConvertAAndB(); } void ConvertAAndB() { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); List<AModel> modelAList = new List<AModel>(); for(int i=0;i<200000;i++) { modelAList.Add(new AModel { Id = i + 1, Name = $"Name_{i + 1}", Author = $"Author_{i + 1}", Title = $"Title_{i + 1}", ISBN = $"ISBN_{i + 1}", Topic = $"Topic_{i + 1}" }); } watch.Stop(); System.Diagnostics.Debug.WriteLine($"Generate :{modelAList.Count},milliseconds:{watch.ElapsedMilliseconds}"); List<BModel> modelBList = new List<BModel>(); watch.Restart(); //for(int i=0;i<200000;i++) //{ // modelBList.Add(new BModel // { // Id = modelAList[i].Id, // Name = modelAList[i].Name, // Author = modelAList[i].Author, // Title = modelAList[i].Title, // Topic = modelAList[i].Topic, // ISBN = modelAList[i].ISBN // }); //} Parallel.ForEach(modelAList, x => { modelBList.Add(new BModel { Id = x.Id, Name = x.Name, Author = x.Author, Title = x.Title, Topic = x.Topic, ISBN = x.ISBN }); }); watch.Stop(); System.Diagnostics.Debug.WriteLine($"Convert :{modelBList.Count},milliseconds:{watch.ElapsedMilliseconds}"); } } class AModel { public int Id { get; set; } public string Name { get; set; } public string Author { get; set; } public string Title { get; set; } public string ISBN { get; set; } public string Topic { get; set; } } class BModel { public int Id { get; set; } public string Name { get; set; } public string Author { get; set; } public string Title { get; set; } public string ISBN { get; set; } public string Topic { get; set; } } }

 

 

 

Plan A:

You're accessing the list by different threads, but a list is not threadsafe:

You could lock the list with:

lock(modelBList) 

{

}

Parallel.ForEach(modelAList, x =>
{
    lock(modelBList) 
    {
        modelBList.Add(new BModel
        {
            Id = x.Id,
            Name = x.Name,
            Author = x.Author,
            Title = x.Title,
            Topic = x.Topic,
            ISBN = x.ISBN
        });
    } 
});

 

Plan B:

ConcurrentBag

 ConcurrentBag<BModel> modelBList = new ConcurrentBag<BModel>();

void ConvertAAndB()
{
    System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
    watch.Start();
    List<AModel> modelAList = new List<AModel>();
    for(int i=0;i<200000;i++)
    {
        modelAList.Add(new AModel
        {
            Id = i + 1,
            Name = $"Name_{i + 1}",
            Author = $"Author_{i + 1}",
            Title = $"Title_{i + 1}",
            ISBN = $"ISBN_{i + 1}",
            Topic = $"Topic_{i + 1}"
        });
    }
    watch.Stop();
    System.Diagnostics.Debug.WriteLine($"Generate :{modelAList.Count},milliseconds:{watch.ElapsedMilliseconds}");

    //List<BModel> modelBList = new List<BModel>();
    ConcurrentBag<BModel> modelBList = new ConcurrentBag<BModel>();
    watch.Restart();
    //for(int i=0;i<200000;i++)
    //{
    //    modelBList.Add(new BModel
    //    {
    //        Id = modelAList[i].Id,
    //        Name = modelAList[i].Name,
    //        Author = modelAList[i].Author,
    //        Title = modelAList[i].Title,
    //        Topic = modelAList[i].Topic,
    //        ISBN = modelAList[i].ISBN
    //    });
    //}
    Parallel.ForEach(modelAList, x =>
    {
        modelBList.Add(new BModel
        {
            Id = x.Id,
            Name = x.Name,
            Author = x.Author,
            Title = x.Title,
            Topic = x.Topic,
            ISBN = x.ISBN
        });
    });
    watch.Stop();
    System.Diagnostics.Debug.WriteLine($"Convert :{modelBList.Count},milliseconds:{watch.ElapsedMilliseconds}");

}

 

 

Copy from https://stackoverflow.com/questions/57785475/source-array-was-not-long-enough-check-srcindex-and-length-and-the-arrays-low

 

标签:set,get,modelBList,System,long,length,using,array,public
From: https://www.cnblogs.com/Fred1987/p/18232598

相关文章

  • 为什么MySQL的information_schema.tables字段index_length显示为0?
     为什么MySQL的information_schema.tables字段index_length显示为0? 测试版本为:MySQL社区版8.0.36 分情况1:innodb引擎的表是索引组织表,按照主键进行顺序存放。则表是索引,索引是表,index_length不会有值。如下,创建一个表,并追加主键,查看索引情况。(root@localhost11:02:2......
  • 718-Maximum length of repeated subarry
    题目描述链接:https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/Giventwointegerarrays nums1 and nums2,return themaximumlengthofasubarraythatappearsin both arrays.解释:给定两个数组nums1和nums2,求两个数组的最长公......
  • WPF draw ellipse as array or matrix
    <Windowx:Class="WpfApp133.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • idea编辑器中 This document contents very long lines..........
    背景:在idea编辑器中引入压缩后的js文件在子目录中,有如下提示在控制台-元素中js并未加载上 另外,同文件夹下未压缩的js文件可正常加载。可以,排除,路径问题。 解决问题:压缩的js,得放到根目录,可能是文件太大了,需要预加载 ......
  • LeetCode 720. Longest Word in Dictionary
    原题链接在这里:https://leetcode.com/problems/longest-word-in-dictionary/description/题目:Givenanarrayofstrings words representinganEnglishDictionary,return thelongestwordin words thatcanbebuiltonecharacteratatimebyotherwordsin wor......
  • Leetcode 3171. Find Subarray With Bitwise AND Closest to K
    Leetcode3171.FindSubarrayWithBitwiseANDClosesttoK1.解题思路2.代码实现题目链接:3171.FindSubarrayWithBitwiseANDClosesttoK1.解题思路这道题坦率地说让我感觉很挫败,又一次没有自力搞定,是看了大佬们的答案才搞定的……知道比没有搞定更难受的......
  • 集合类源码浅析のArrayList
    源码分析路线图:初级部分:ArrayList->LinkedList->Vector->HashMap(红黑树数据结构,如何翻转,变色,手写红黑树)->ConcurrentHashMap中级部分:Spring->SpringMVC->SpringBoot->Mybatis核心类源码高级部分:中间件源码(有生之年系列)第一篇,从最简单的ArrayList入手分析1、成员变量......
  • 在 Python 中转换为 np.array 时的内存饱和与内核重启
    在将处理过的数据转换为numpy数组时,我遇到了内存问题。我有57GB内存,但内存很快就饱和了,内核会在np.array(processed_X)处重启。以下是我的代码:importnumpyasnp导入scipy.signalfromskimage.transformimportresizefromtqdmimporttqdmdefapply_stft(signal,n......
  • B. 378QAQ and Mocha's Array
    原题链接题解数组内是否存在两个数,使得数组内所有元素都是它们俩其中之一的倍数1.最小的元素肯定要选,因为没人是它的倍数2.把所有能被最小元素整除的元素去掉之后,再选一个最小数code#include<bits/stdc++.h>#definelllonglongusingnamespacestd;lla[100005];intm......
  • A. Bazoka and Mocha's Array
    原题链接题解和破环成链的过程很像code#include<bits/stdc++.h>usingnamespacestd;inta[105];intmain(){intt;cin>>t;while(t--){intn;cin>>n;intflag=0;for(inti=1;i<=n;i++){......