I am trying to loop through an integer array using C# Iterators. The program below loops through the non-generic Iterator but not through the generic iterator. I am unable to figure out the problem.
namespace SampleCSApp
{
class Program
{
static void Main(string[] args)
{
var output = new int[10];
ParallelLoopResult LoopResult =
Parallel.For(1, 10, (int i, ParallelLoopState loop) =>
{
if (i == 5)
{
loop.Break();
return;
}
output[i] = Compute(i);
});
long CompletedUpto = 10;
if (!LoopResult.IsCompleted && LoopResult.LowestBreakIteration.HasValue)
CompletedUpto = LoopResult.LowestBreakIteration.Value;
string format = string.Format(CompletedUpto == 10 ? "Ran to Completion" : "Completed upto:{0}",CompletedUpto);
Console.WriteLine(format);
int index = 0;
// This does not work.
foreach (var i in Iterate<int>(() => 0, i => i < output.Length, i => output[i], i => i++))
Console.WriteLine("output[{0}]:{1}", index++, i);
// This works.
foreach(var i in Iterate(output))
Console.WriteLine("output[{0}]:{1}", index++, i);
}
public static IEnumerable<T> Iterate<T>(Func<T> initialize, Func<T, bool> condition, Func<T, T> body, Func<T, T> update)
{
for (T i = initialize(); condition(i); i = update(i))
yield return body(i);
}
public static IEnumerable<int> Iterate(int[] output)
{
for (int i = 0; i < output.Length; i++)
yield return output[i];
}
private static int Compute(int i)
{
return i * i;
}
}
}
I think the postincrement is the problem?
If your function returns i++, will it not return i then post increment the unshared variable?
ie change it to
Does that help?