其他分享
首页 > 其他分享> > PLINQ查询和LINQ查询

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}");
  }
}

标签:Console,students,Age,watch,LINQ,查询,WriteLine,var,PLINQ
来源: https://www.cnblogs.com/gibschen/p/15767268.html