是否有可能使用并行任务并返回IEnumerable的方法?

本文关键字:方法 IEnumerable 返回 有可能 并行任务 是否 | 更新日期: 2023-09-27 18:15:31

我希望该方法并行执行任务,当任务完成时"yield返回"结果。有可能有这样的东西吗?

   public IEnumerable<string> GetAllLogs()
   {
     var computers = GetComputers()
                            .Where(cpt => cpt.IsOnline);
     Parallel.ForEach(computers, c => c.GetLogs());
     // How to 'yield return' ?
   }

谢谢! !

编辑:

也许我以前的例子在这里不够明确,一个新的(我希望)更明确的;-)

我想知道如何并行GetAllLogs方法:

public class ComputerManager
{
    public IEnumerable<string> GetAllLogs(IEnumerable<IComputer> computers)
    {
        foreach (var cpt in computers)
        {
            // How to Parallelize the foreach bloc and 
            // use a 'yield return' to keep the IEnumerable<string> return type ?
            foreach (var log in cpt.GetLogs())
            {
                yield return log;
            }
        }
    }
}
    static void Main(string[] args)
    {
        ComputerManager cm = new ComputerManager();
        IComputer[] computers = new IComputer[] {new Computer(), new Computer2(), new Computer3(), new Computer4() };
        Stopwatch sw = new Stopwatch();
        sw.Start();
        foreach (string s in cm.GetAllLogs(computers))
        {
            Console.WriteLine(s);
        }
        sw.Stop();
        Console.WriteLine("Terminé en : {0}" , sw.ElapsedMilliseconds);
        Console.Read();
    }
}
public interface IComputer
{
    IEnumerable<string> GetLogs();
}

public class Computer : IComputer
{
    public IEnumerable<string> GetLogs()
    {
        string[] alphabet = new string[] { "a", "b", "c", "d", "e"};
        foreach (var letter in alphabet)
        {
            Thread.Sleep(1000);
            yield return letter;
        }
    }
}
public class Computer2 : IComputer
{
    public IEnumerable<string> GetLogs()
    {
        string[] figures = new string[] { "1", "2", "3", "4", "5" };
        foreach (var figure in figures)
        {
            Thread.Sleep(1000);
            yield return figure;
        }
    }
}

public class Computer3 : IComputer
{
    public IEnumerable<string> GetLogs()
    {
        string[] greekAlphabet = new string[] { "alpha", "beta", "gamma", "delta", "epsilon" };
        foreach (var letter in greekAlphabet)
        {
            Thread.Sleep(1000);
            yield return letter;
        }
    }
}

public class Computer4 : IComputer
{
    public IEnumerable<string> GetLogs()
    {
        string[] romanFigures = new string[] { "I", "II", "III", "IV", "V" };
        foreach (var s in romanFigures)
        {
            Thread.Sleep(1000);
            yield return s;
        }
    }
}

是否有可能使用并行任务并返回IEnumerable<T>的方法?

Reed Copsey(来自SO的用户)在MSDN论坛上发布了这篇文章。这可能会有帮助!

http://social.msdn.microsoft.com/forums/en au/parallelextensions/thread/3352a322 af6f - 4105 b25c - 9978 bd85f162

// In your source, you use yield
public ClassImplementingIEnumerable: IEnumerable<int>
{
 public IEnumerable<int> GetSource()
 {
       for (int i=0;i<1000;++i)
           yield return i;
 }
}

public class ParallelProcessingConsumer {
public void SomeMethod(ClassImplementingIEnumerable sourceProvider)
{
      Parallel.ForEach(sourceProvider.GetSource(), parallelOptions, (i, loopState) => 
      {  
         // Do work in parallel!
      });
}

如果您想在并行执行开始时立即返回:

public class ComputerManager
{
    public IEnumerable<string> GetAllLogs(IEnumerable<IComputer> computers)
    {
        return computers.AsParallel().SelectMany(c => c.GetLogs());
    }
}

如果你想在并行执行结束时返回:

public class ComputerManager
{
    public IEnumerable<string> GetAllLogs(IEnumerable<IComputer> computers)
    {
        return computers.AsParallel().SelectMany(c => c.GetLogs()).ToArray();
    }
}

这个适合我:

  • 在并行任务中。在ConcurrentQueue中获取项目转换为待处理。
  • 任务有一个继续标记标志表示任务结束。
  • 与任务在同一线程中执行结束while dequeue并生成

快速和优秀的结果:

Task.Factory.StartNew (() =>
{
    Parallel.ForEach<string> (TextHelper.ReadLines(FileName), ProcessHelper.DefaultParallelOptions,
    (string currentLine) =>
    {
        // Read line, validate and enqeue to an instance of FileLineData (custom class)
    });
}).
ContinueWith 
(
    ic => isCompleted = true 
);

while (!isCompleted || qlines.Count > 0)
{
    if (qlines.TryDequeue (out returnLine))
    {
        yield return returnLine;
    }
}
相关文章: