如何使IEnumerable方法成为并行方法 [英] How to make a IEnumerable method parallel method

查看:112
本文介绍了如何使IEnumerable方法成为并行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此操作发布,我想并行化此方法:

Following to this post, I want parallelize this method :

    public IEnumerable<string> GetAllLogs(IEnumerable<IComputer> computers)
    {
        foreach (var cpt in computers)
        {
            foreach (var log in cpt.GetLogs())
            {
                yield return log;
            }
        }
    }

当方法GetLogs之一完成时,我希望方法"yield返回"日志.如果我有4台计算机,它们返回:

I want the method "yield returns" a log when one of the method GetLogs is finished. If I have 4 computers which returns :

  • 计算机01:"a","b","c","d","e"
  • 计算机02:"1","2","3","4","5"
  • 计算机03:"alpha","beta","gamma","delta","epsilon"
  • 计算机04:"I","II","III","IV","V"

使用顺序方法",输出为:

With the "sequential method", the output is :

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).

And the methods runs in 20 seconds. there is a Thread.Sleep(1000) in the GetLogs method.

我希望输出看起来像这样:

I want the output looks like this :

III
a
4
gamma
b
c
IV
5
d
II
beta
e
1
2
delta
alpha
3
epsilon
I

并在几秒钟内运行.

我要方法返回IEnumerable

I want to the methods returns an IEnumerable

推荐答案

这是您需要的:

public IEnumerable<string> GetAllLogsParallel(IEnumerable<IComputer> computers)
{
    return computers
        .AsParallel()
        .SelectMany(cpt => cpt.GetLogs());
}

如果要同时开始处理4个computer -s,则可以调整并行度,如下所示:

If you want to start processing of 4 computer-s at the same time you can adjust the degree of parallelism like this:

public IEnumerable<string> GetAllLogsParallel(IEnumerable<IComputer> computers)
{
    return computers
        .AsParallel()
        .WithDegreeOfParallelism(4)
        .SelectMany(cpt => cpt.GetLogs());
}

以下只是为了便于理解的简化说明. 要了解有关此内容的更多信息,请访问MSDN上的 PLINQ(并行LINQ) .

Following is a simplified explanation just for understanding. To learn more about that just visit PLINQ (Parallel LINQ) at MSDN.

好吧,.AsParallel()-将computers可枚举分为4部分,并同时启动4个线程.每个线程为每个computer执行cpt.GetLogs().结果为IEnumerable<IEnumerable<string>>-可枚举的枚举. SelectMany()用于通过串联内部可枚举并消除外部可枚举来拉平此列表.结果按到达顺序自动合并回主线程.

Well, .AsParallel() - splits the computers enumerable into 4 parts and starts 4 threads at the same time. Each thread executes cpt.GetLogs() for each computer. The result is IEnumerable<IEnumerable<string>> - enumerable of enumerables. SelectMany() is used to flatten this list by concatenating inner enumerables and eliminating outer ones. Results are merged back automatically into the main thread in the order of their arrival.

这篇关于如何使IEnumerable方法成为并行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆