【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也是並行處理。速度上絕對是快的,但是相對輸出的順序是不確定的。



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