简体   繁体   English

在Parallel.ForEach中传递列表

[英]Pass in lists in the Parallel.ForEach

This is the first time I try to use the "Parallel.ForEach" loop to see if I can improve performance using many cores in the system. 这是我第一次尝试使用“ Parallel.ForEach”循环来查看是否可以使用系统中的许多内核来提高性能。 I have tried to look at MSDN and other examples but I can't find a way to pass in 3 lists as below. 我试图看一下MSDN和其他示例,但是找不到以下3种列表的传递方法。

How can this loop be exchanged with a Parallel.ForEach loop? 如何使用Parallel.ForEach循环交换此循环? I think I am looking for the basics how to pass in all those 3 lists so I can work with them in the Parallel.ForEach loop? 我想我正在寻找如何传递所有这三个列表的基础知识,以便可以在Parallel.ForEach循环中使用它们?

Thank you! 谢谢!

        List<double> nums = new List<double> { 0.0005, 0.00035, 0.00205 };
        List<double> list1 = new List<double>();
        List<double> list2 = new List<double>();
        List<double> list3 = new List<double>(); Random random = new Random(); double calc1 = 0;
        List<double> resultLIST = new List<double>();
        for (int i = 0; i < 4000000; i++)
        {
            list1.Add(nums[random.Next(0, 7)]);
            list2.Add(nums[random.Next(0, 7)]);
            list3.Add(nums[random.Next(0, 7)]);
        }

        //How can the below loop be replaced with a: Parallel.ForEach loop?
        for (int i = 0; i < list1.Count; i++)
        {
            calc1 = list1[i] * list2[i] * list3[i];
            resultLIST.Add(calc1);
        }

        //Now sort the list 
        resultLIST.Sort();

        //Here I will write "resultLIST" to a .txt file

Personally, I would use LINQ with AsParallel : 我个人将LINQ与AsParallel使用:

var result = Enumerable.Range(0, list1.Count)
    .AsParallel()
    .Select(index => list1[index] + list2[index] + list3[index])
    .OrderBy(v => v)
    .ToList();

Note that list1 , list2 and list3 are not expected to change during this calculation. 注意,在此计算期间,预计list1list2list3不会发生变化。

You use the Parallel.Foreach when the operations on each list can run independently in parallel. 当每个列表上的操作可以并行运行时,可以使用Parallel.Foreach。 In your case you cannot. 就您而言,您不能。 Also remember using Parallel.Foreach or AsParallel for trivial operations like * or + can actual degrade performance because there is more overhead. 还要记住,对诸如*或+之类的琐碎操作使用Parallel.Foreach或AsParallel可能会降低性能,因为存在更多开销。

In your case the best approach will be to split all three lists with 1000000 elements each. 在您的情况下,最好的方法是将所有三个列表均分为1000000个元素。 Add them into an array of array and call Parallel.Foreach on them. 将它们添加到一个数组数组中,并对其调用Parallel.Foreach。 That way you will have 4 threads doing 1000000 operations each and if your machine has 4 cores they can run independently on each core. 这样,您将拥有4个线程,每个线程执行1000000次操作,如果您的计算机具有4个内核,则它们可以在每个内核上独立运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM