PLINQ查询和LINQ查询

PLINQ查询和LINQ查询也就是并行和串行的区别:

基本类:

复制代码

public class Student
{
 public int Id { get; set; }
 public string Name { get; set; }
 public int Age { get; set; }
 public DateTime CreateTime { get; set; }
}

 

复制代码

 

具体实现演变:

复制代码

public partial class Program
{
 private static void Sample04()
 {

 //线程安全字典
 var students = new ConcurrentDictionary<int, Student>();
 // 并行生成1000万条数据
 Parallel.For(0, 10_000_000, (i) =>
 {
 var single = new Student
 {
  Id = i,
  Name = "name" + i,
  Age = i % 100,
  CreateTime = DateTime.Now.AddSeconds(i)
 };
  students.TryAdd(i, single);
 });
 Console.WriteLine("数据已生成");

 // PLINQ查询
 var watch = new Stopwatch();
 watch.Start();
 var query1 = (from n in students.Values.AsParallel()
 where n.Age > 18 && n.Age < 80
 select n).ToList();

 watch.Stop();
 Console.WriteLine("PLINQ耗时:{0}", watch.ElapsedMilliseconds);

 // LINQ查询
 watch.Restart();
 var query2 = (from n in students.Values
 where n.Age > 18 && n.Age < 80
 select n).ToList();

 watch.Stop();
 Console.WriteLine("LINQ耗时:{0}", watch.ElapsedMilliseconds);
 }

 private static void LinqTread()
{
var students = new ConcurrentDictionary<int, Student>();
Parallel.For(0, 10, (i) =>
{
 var single = new Student
 {
 Id = i,
 Name = "name" + i,
 Age = i % 100,
 CreateTime = DateTime.Now.AddSeconds(i)
 };
 students.TryAdd(i, single);
 });
 Console.WriteLine("数据生成结束");

 // 测试PLNQ与LINQ查询
 var query = from n in students.Values.AsParallel()
 select new {Name = n.Name, ThreadId = Thread.CurrentThread.ManagedThreadId};

 foreach (var o in query)
 {
 Console.WriteLine($"{o} - from ThreadId = {Thread.CurrentThread.ManagedThreadId}");
 }

  Console.WriteLine($"CurrentThreadId:{Thread.CurrentThread.ManagedThreadId}");
  }
}

复制代码
posted @   根仔  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示