【C#】59. AsParallel() 与 ForAll

平时经常会用到LINQ,这里介绍的方法可以有效地使用并行查询来加快查询速度(AsParallel),同时通过使用ForAll来对结果进行并行处理。


GetTpyes:通过反射,从当前Assembllies中的所有组件中找出名称以“Web”开头的类型名称。

static IEnumerable<string> GetTypes()
{
return from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetExportedTypes()
where type.Name.StartsWith("Web")
select type.Name;

}

EmulateProcessing:模拟查询操作中的处理操作,作用是 为了让大家看到select处理是发生在哪个线程上

static string EmulateProcessing(string typeName)
{
Thread.Sleep(TimeSpan.FromMilliseconds(150));
Console.WriteLine("{0} type was processed on a thread id {1}",typeName, Thread.CurrentThread.ManagedThreadId);
return typeName;
}

PrintInfo:对查询后的结果进行打印

static void PrintInfo(string typeName)
{
Thread.Sleep(TimeSpan.FromMilliseconds(150));
Console.WriteLine("{0} type was printed on a thread id {1}",typeName, Thread.CurrentThread.ManagedThreadId);
}

调用程序:

sw.Start();
var parallelQuery = from t in GetTypes().AsParallel() select EmulateProcessing(t);


parallelQuery.ForAll(PrintInfo);


sw.Stop();
Console.WriteLine("---");
Console.WriteLine("Parallel LINQ query. The results are being processed in parallel");
Console.WriteLine("Time elapsed: {0}", sw.Elapsed);
Console.WriteLine("Press ENTER to continue....");
Console.ReadLine();
Console.Clear();
sw.Reset();



很明显地可以看到由于使用了AsParallel(),查询处理使用了并行处理;而由于使用了ForAll()操作,因此print也是并行处理。速度上绝对是快的,但是相对输出的顺序是不确定的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值