Reputation: 55
public static void Main (string[] args)
{
int k = 0;
int i = 3;
var loopRes = Parallel.For (0, 20, (J) =>
{
k = i / J;
Console.WriteLine ("Result After division " + J + " = " + k);
}
);
if (loopRes.IsCompleted) {
Console.WriteLine ("Loop was successful");
}
if (loopRes.LowestBreakIteration.HasValue) {
Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value);
}
}
As of i read on the internet i can find 2 properties for Parallel.For & Parallel.Foreach
For me first property is working fine. but when it comes to the situation where 3/0 then it will give the divided by zero error. so the second if loop should give me the number of LowestBreakIteration but it is throwing an error. please let me know if any body has come accross the same problem and solved it!!.
Also please explain what is the main purpose of those two properties. On what situations it wil be helpful.
Hope to hear from some one soon.
Upvotes: 3
Views: 267
Reputation: 67898
It's because it's throwing an exception, change your loop just a tad:
public static void Main (string[] args)
{
int k = 0;
int i = 3;
var loopRes = Parallel.For (0, 20, (J, loopState) =>
{
try { k = i / J; }
catch { loopState.Break(); }
Console.WriteLine ("Result After division " + J + " = " + k);
}
);
if (loopRes.IsCompleted) {
Console.WriteLine ("Loop was successful");
}
if (loopRes.LowestBreakIteration.HasValue) {
Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value);
}
}
Upvotes: 1
Reputation: 16708
You can see how the maximum iteration number is affected by calls to the Break method by viewing the LowestBreakIteration property of the ParallelLoopState object, as shown below:
Parallel.For(1, 20, (i, pls) =>
{
Console.WriteLine(string.Format(
"i={0} LowestBreakIteration={1}", i, pls.LowestBreakIteration));
if (i >= 15)
{
pls.Break();
}
});
/* OUTPUT
i=10 LowestBreakIteration=
i=11 LowestBreakIteration=
i=19 LowestBreakIteration=
i=1 LowestBreakIteration=
i=2 LowestBreakIteration=19
i=3 LowestBreakIteration=19
i=6 LowestBreakIteration=19
i=7 LowestBreakIteration=19
i=8 LowestBreakIteration=19
i=9 LowestBreakIteration=19
i=12 LowestBreakIteration=19
i=13 LowestBreakIteration=19
i=14 LowestBreakIteration=19
i=15 LowestBreakIteration=19
i=4 LowestBreakIteration=19
i=5 LowestBreakIteration=15
*/
Reference: http://www.blackwasp.co.uk/ParallelLoopBreak_2.aspx
Upvotes: 0