[英]How to make a IEnumerable method parallel method
在這篇文章之后,我想並行化這個方法:
public IEnumerable<string> GetAllLogs(IEnumerable<IComputer> computers)
{
foreach (var cpt in computers)
{
foreach (var log in cpt.GetLogs())
{
yield return log;
}
}
}
當 GetLogs 方法之一完成時,我希望方法“收益返回”一個日志。 如果我有 4 台計算機返回:
使用“順序方法”,輸出為:
a
b
c
d
e
1
2
3
4
5
alpha
beta
gamma
delta
epsilon
I
II
III
IV
V
這些方法在 20 秒內運行。 GetLogs
方法中有一個Thread.Sleep(1000)
。
我希望輸出如下所示:
III
a
4
gamma
b
c
IV
5
d
II
beta
e
1
2
delta
alpha
3
epsilon
I
並在幾秒鍾內運行。
我想方法返回一個 IEnumerable
這是你需要的:
public IEnumerable<string> GetAllLogsParallel(IEnumerable<IComputer> computers)
{
return computers
.AsParallel()
.SelectMany(cpt => cpt.GetLogs());
}
如果要同時開始處理 4 個computer
-s,可以這樣調整並行度:
public IEnumerable<string> GetAllLogsParallel(IEnumerable<IComputer> computers)
{
return computers
.AsParallel()
.WithDegreeOfParallelism(4)
.SelectMany(cpt => cpt.GetLogs());
}
以下是簡單的解釋,僅供理解。 要了解更多信息,請訪問 MSDN 上的PLINQ(並行 LINQ) 。
好吧, .AsParallel()
- 將可枚舉的computers
分成 4 個部分並同時啟動 4 個線程。 每個線程為每台computer
執行cpt.GetLogs()
。 結果是IEnumerable<IEnumerable<string>>
- enumerable of enumerables。 SelectMany()
用於通過連接內部枚舉和消除外部枚舉來展平此列表。 結果按照到達的順序自動合並回主線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.