Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.For Properties

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

  1. IsCompleted
  2. LowestBreakIteration

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.

like image 915
user1737936 Avatar asked Nov 24 '25 01:11

user1737936


1 Answers

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); 
    } 
}  
like image 179
Mike Perrenoud Avatar answered Nov 25 '25 15:11

Mike Perrenoud