简体   繁体   English

如何在C#中使用TPL(任务并行库)加速填充列表

[英]how to speed up populating a list using TPL(task parallel library) in c#

I have following piece of code 我有以下代码

List<GridVM> _itemsSource = new List<GridVM>();

  foreach(var shelf in Network.Shelves)
   {
        foreach(var equipment in shelf.Equipment)
        {
          var gridVM= new GridVM(equipment);
          itemSource.Add(gridVM);
         }
   }

here _itemSource is a collection that is going to be data source for a grid. _itemSource是一个集合,它将成为网格的数据源。

now creating each vm object for each equipment is taking little bit time ~~around 8 seconds. 现在为每个设备创建每个vm对象大约需要8秒钟的时间。 I want to speed up grid data source population using TPL by running inner forloop in different thread and add the vm to the main collection of _itemSource. 我想通过在不同线程中运行内部forloop并将vm添加到_itemSource的主集合中,从而使用TPL加快网格数据源的填充。

How to achieves so using TPL. 如何使用TPL实现。 Will it really speed up my job considering the facts thread overheads and locking overheads. 考虑到线程开销和锁定开销的事实,是否真的可以加快我的工作速度? I can convert current list item source to ConcurrentList or ConcurrntBag. 我可以将当​​前列表项源转换为ConcurrentList或ConcurrntBag。 but same question :-will it really give any boost or not. 但同样的问题:-真的会有所助益吗? if not, then I am interest to know why?? 如果没有,那么我很想知道为什么?

You can easily parallelize your code using PLINQ (aka Parallel Linq): 您可以使用PLINQ(又名Parallel Linq)轻松并行化代码:

var _itemsSource = Network.Shelves
    .SelectMany(s => s.Equipment)
    .AsParallel()
    .Select(e => new GridVM(e))
    .ToList();

It may execute faster if the constructor takes time. 如果构造函数需要一些时间,它可能会执行得更快。 If the overhead is just "adding items to a list" then you'll gain nothing. 如果开销仅仅是“将项目添加到列表”,那么您将一无所获。 That said, if it takes 8 seconds just to add items to the list, then you definitely have other problems, such as memory consumption. 也就是说,如果仅将项目添加到列表需要8秒钟,那么您肯定还有其他问题,例如内存消耗。

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

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