【发布时间】:2011-11-24 09:30:40
【问题描述】:
我希望该方法并行执行任务,并在任务完成后“返回”结果。有没有可能有这样的东西:
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;
}
}
}
【问题讨论】:
-
yield “任务完成时”或“任务完成时”?