是否可以使用并行任务的方法并返回IEnumerable <t> </t>

时间:2011-11-24 09:30:40

标签: c# task-parallel-library

我希望该方法并行执行任务,并在任务完成时执行任务&#34; yield return&#34;结果。有可能有这样的东西:

   public IEnumerable<string> GetAllLogs()
   {
     var computers = GetComputers()
                            .Where(cpt => cpt.IsOnline);

     Parallel.ForEach(computers, c => c.GetLogs());

     // How to 'yield return' ?
   }

Thx !!!

编辑:

也许我以前的样本在这里不够明确一个新的和(我希望)更明确的一个; - )

我想知道如何平行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;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

Reed Copsey(来自SO的用户)在MSDN论坛上发布了此消息。这可能会有所帮助!

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

// 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!
      });
}

答案 1 :(得分:2)

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

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();
    }
}

答案 2 :(得分:0)

这对我有用:

  • 在Parallel.Foreach中的任务中,在ConcurrentQueue中将项目排队 转化为待处理。
  • 任务有一个标志着的继续 该任务的标志结束。
  • 与任务执行相同的线程 结束了一段时间的出队和收益

快速而优异的结果:

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;
    }
}