如何将foreach转换为每个并行 [英] How to convert foreach to parallel for each

查看:144
本文介绍了如何将foreach转换为每个并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的z中包含两个对象列表



我如何才能完成这个



< b>我尝试了什么:



In the following z contains two list of objects

How i can accomplish this

What I have tried:

z{
list<row>
list<yy>
}
foreach(var y in z)
                           {
                                DataRow oldRow = y.row;
                                oldRow.SetField<string>("AMOUNT", y.yy.Value);
                           }

推荐答案

并行可以通过两种方式完成



1.并行类

2. PLINQ(并行LINQ)



以下是使用Parallel类的代码:

Parallelism can be accomplish in two ways

1. Parallel class
2. PLINQ (Parallel LINQ)

Here is the code using Parallel class:
string[] lines = File.ReadAllLines("filePath");
List<string> listLines = new List<string>(lines);
Parallel.ForEach(listLines, line =>
{
    //Your stuff
	callMethod(line);
});
</string></string>



不要盲目地选择并行类来遍历列表,否则可能会给你带来性能开销。当你有以下要求时使用Parallel类:



执行并行执行。

Parallel.ForEach使用多个线程。

Parallel.ForEach在.Net 4.0及以上框架中定义。

执行速度更快。



注意:在你的如果您没有执行任何操作,则无需使用Parallel类。如果您看到我的示例,则调用循环内的方法以使其符合要求。


Don't choose blindly to choose Parallel class to loop over a list otherwise it may throw you performance overhead. Use Parallel class when you have following requirement:

Execution takes place in parallel way.
Parallel.ForEach uses multiple Threads.
Parallel.ForEach is defined in .Net 4.0 and above frameworks.
Execution is faster.

Note: In your if you are not performing any action then there is no need to use Parallel class. If you see my example it is calling the method inside the loop so it suits the requirement.


这篇关于如何将foreach转换为每个并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆