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

查看:23
本文介绍了如何使 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 方法之一完成时,我希望方法收益返回"一个日志.如果我有 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 个线程.每个线程为每台计算机执行cpt.GetLogs().结果是 IEnumerable> - enumerable of enumerable.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天全站免登陆