5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq
5天玩转C#并行和多线程编程系列文章目录
5天玩转C#并行和多线程编程 —— 第一天 认识Parallel
5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent; namespace ThreadPool
{
public class PEnumerable
{
public static void ListWithParallel()
{
List<int> list = new List<int>();
Parallel.For(, , item =>
{
list.Add(item);
});
Console.WriteLine("List's count is {0}",list.Count());
}
}
}
点击F5运行,得到如下结果:

看到结果中显示的5851,但是我们循环的是10000次啊!怎么结果不对呢?这是因为List<T>是非线程安全集合,意思就是说所有的线程都可以修改他的值。
下面我们来看下并行集合 —— 线程安全集合,在System.Collections.Concurrent命名空间中,首先来看一下ConcurrentBag<T>泛型集合,其用法和List<T>类似,先来写个方法测试一下:
public static void ConcurrentBagWithPallel()
{
ConcurrentBag<int> list = new ConcurrentBag<int>();
Parallel.For(, , item =>
{
list.Add(item);
});
Console.WriteLine("ConcurrentBag's count is {0}", list.Count());
}
同时执行两个方法,结果如下:

可以看到,ConcurrentBag集合的结果是正确的。下面我们修改代码看看ConcurrentBag里面的数据到底是怎么存放的,修改代码如下:
public static void ConcurrentBagWithPallel()
{
ConcurrentBag<int> list = new ConcurrentBag<int>();
Parallel.For(, , item =>
{
list.Add(item);
});
Console.WriteLine("ConcurrentBag's count is {0}", list.Count());
int n = ;
foreach(int i in list)
{
if (n > )
break;
n++;
Console.WriteLine("Item[{0}] = {1}",n,i);
}
Console.WriteLine("ConcurrentBag's max item is {0}", list.Max()); }
先来看一下运行结果:

可以看到,ConcurrentBag中的数据并不是按照顺序排列的,顺序是乱的,随机的。我们平时使用的Max、First、Last等linq方法都还有。其时分类似Enumerable的用法,大家可以参考微软的MSDN了解它的具体用法。
关于线程安全的集合还有很多,和我们平时用的集合都差不多,比如类似Dictionary的ConcurrentDictionary,还有ConcurrentStack,ConcurrentQueue等。
1、AsParallel
前面了解了并行的For和foreach,今天就来看一下Linq的并行版本是怎么样吧?为了测试,我们添加一个Custom类,代码如下:
public class Custom
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
写如下测试代码:
public static void TestPLinq()
{
Stopwatch sw = new Stopwatch();
List<Custom> customs = new List<Custom>();
for (int i = ; i < ; i++)
{
customs.Add(new Custom() { Name = "Jack", Age = , Address = "NewYork" });
customs.Add(new Custom() { Name = "Jime", Age = , Address = "China" });
customs.Add(new Custom() { Name = "Tina", Age = , Address = "ShangHai" });
customs.Add(new Custom() { Name = "Luo", Age = , Address = "Beijing" });
customs.Add(new Custom() { Name = "Wang", Age = , Address = "Guangdong" });
customs.Add(new Custom() { Name = "Feng", Age = , Address = "YunNan" });
} sw.Start();
var result = customs.Where<Custom>(c => c.Age > ).ToList();
sw.Stop();
Console.WriteLine("Linq time is {0}.",sw.ElapsedMilliseconds); sw.Restart();
sw.Start();
var result2 = customs.AsParallel().Where<Custom>(c => c.Age > ).ToList();
sw.Stop();
Console.WriteLine("Parallel Linq time is {0}.", sw.ElapsedMilliseconds);
}
其实也就是加了一个AsParallel()方法,下面来看下运行结果:

时间相差了一倍,不过有时候不会相差这么多,要看系统当前的资源利用率。大家可以多测试一下。
其实,AsParallel()这个方法可以应用与任何集合,包括List<T>集合,从而提高查询速度和系统性能。
2、GroupBy方法
在项目中,我们经常要对数据做处理,比如分组统计,我们知道在linq中也可以实现,今天来学习一下新的ToLookup方法,写一个测试方法,代码如下:
public static void OrderByTest()
{
Stopwatch stopWatch = new Stopwatch();
List<Custom> customs = new List<Custom>();
for (int i = ; i < ; i++)
{
customs.Add(new Custom() { Name = "Jack", Age = , Address = "NewYork" });
customs.Add(new Custom() { Name = "Jime", Age = , Address = "China" });
customs.Add(new Custom() { Name = "Tina", Age = , Address = "ShangHai" });
customs.Add(new Custom() { Name = "Luo", Age = , Address = "Beijing" });
customs.Add(new Custom() { Name = "Wang", Age = , Address = "Guangdong" });
customs.Add(new Custom() { Name = "Feng", Age = , Address = "YunNan" });
} stopWatch.Restart();
var groupByAge = customs.GroupBy(item => item.Age).ToList();
foreach (var item in groupByAge)
{
Console.WriteLine("Age={0},count = {1}", item.Key, item.Count());
}
stopWatch.Stop(); Console.WriteLine("Linq group by time is: " + stopWatch.ElapsedMilliseconds); stopWatch.Restart();
var lookupList = customs.ToLookup(i => i.Age);
foreach (var item in lookupList)
{
Console.WriteLine("LookUP:Age={0},count = {1}", item.Key, item.Count());
}
stopWatch.Stop();
Console.WriteLine("LookUp group by time is: " + stopWatch.ElapsedMilliseconds);
}
运行结果如下:

ToLookup方法是将集合转换成一个只读集合,所以在大数据量分组时性能优于List.大家可以查阅相关资料,这里由于篇幅问题,不再细说。
5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq的更多相关文章
- 5天玩转C#并行和多线程编程 —— 第五天 多线程编程大总结
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- 5天玩转C#并行和多线程编程 —— 第四天 Task进阶
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- 5天玩转C#并行和多线程编程 —— 第三天 认识和使用Task
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- 5天玩转C#并行和多线程编程
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 转载 https://www.cnblogs.com/yunfeifei/p/3993401.html
5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...
- C#并行和多线程编程
5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线 ...
- C#并行和多线程编程_(1)认识Parallel
Parallel: 英 [ˈpærəlel] 美 [ˈpærəˌlɛl] ,并联的,并行的. 随着多核时代的到来,并行开发越来越展示出它的强大威力!使用并行程序,充分的利用系统资源,提高程序的性 ...
- python 常见错误和异常 函数 正则表达式及多线程编程
生成随机密码#!/usr/bin/env python import stringfrom random import choice def gen_pass(num=9): all_chs = st ...
随机推荐
- windows7安装python2.7及scrapy
http://www.cnblogs.com/txw1958/archive/2012/07/12/scrapy_installation_introduce.html 第0步:当然是安装python ...
- java开发常用工具
1.eclipse3.6 +浏览器插件+findbug+checkstyle+pmd+svn 2.plsql8.0对数据库的操作,存储过程的调试 3.Securecrt对linux服务器的操作 4.e ...
- 【Mail】JavaMail发送带附件的邮件(二)
上一篇讲了使用JavaMail发送普通邮件([Mail]JavaMail介绍及发送邮件(一)),本例讲发送复杂的邮件(带有附件的邮件) 生成一封复杂的邮件 新建一个JavaWeb的Maven工程,引入 ...
- Trie树的创建、插入、查询的实现
原文:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=28977986&id=3807947 1.什么是Trie树 Tr ...
- [转]了解SQL Server锁争用:NOLOCK 和 ROWLOCK 的秘密_Mr_Indigo的空间
了解SQL Server锁争用:NOLOCK 和 ROWLOCK 的秘密 关系型数据库,如SQL Server,使用锁来避免多用户修改数据时的并发冲突.当一组数据被某个用户锁定时,除非第一个用户结束修 ...
- luogu p1268 树的重量——构造,真正考验编程能力
题目链接:http://www.luogu.org/problem/show?pid=1268#sub -------- 这道题费了我不少心思= =其实思路和标称毫无差别,但是由于不习惯ACM风格的题 ...
- Spring 常用的一些工具类
学习Java的人,或者开发很多项目,都需要使用到Spring 这个框架,这个框架对于java程序员来说.学好spring 就不怕找不到工作.我们时常会写一些工具类,但是有些时候 我们不清楚,我们些的工 ...
- 后台返回字符串类型function的处理 (递归算法)
$(function(){ $.ajax({ type: "post", url: "${ctx}/modules/fos/reference/echart", ...
- 【安装mysql数据库】
方法/步骤 请注意上图中选择Custom选项,这样才能修改安装目录. 请注意为了数据安全,不要把mysql安装在系统盘,如C:盘. 可以在其他盘符下,新建两个文件夹,一个存储mysql的文件, ...
- 解决Get请求的长度限制
错误提示: HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request whe ...