【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也是并行处理。速度上绝对是快的,但是相对输出的顺序是不确定的。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章