From 65a3a0e7fc79f45af700f85d0eec6fe981044ebd Mon Sep 17 00:00:00 2001 From: Boris Rumyantsev Date: Mon, 6 Apr 2020 08:14:59 +0300 Subject: [PATCH] Redundant variable usage Hi! I propose remove lowest variable, because it redundant and we have the same value in result of the loop. Change output with string interpolation. Sorry, not sure about formatting. For sure both changes are not critical. --- .../cs/break1.cs | 68 +++++++++---------- 1 file changed, 32 insertions(+), 36 deletions(-) diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/cs/break1.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/cs/break1.cs index d6d82729f34..627f115ecee 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/cs/break1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallelloopstate/cs/break1.cs @@ -1,49 +1,45 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; public class Example { - public static void Main() - { - var rnd = new Random(); - int breakIndex = rnd.Next(1, 11); - Nullable lowest = new Nullable(); + public static void Main() + { + var rnd = new Random(); + int breakIndex = rnd.Next(1, 11); - Console.WriteLine("Will call Break at iteration {0}\n", - breakIndex); + Console.WriteLine($"Will call Break at iteration {breakIndex}\n"); - var result = Parallel.For(1, 101, (i, state) => { - Console.WriteLine("Beginning iteration {0}", i); - int delay; - Monitor.Enter(rnd); - delay = rnd.Next(1, 1001); - Monitor.Exit(rnd); - Thread.Sleep(delay); - - if (state.ShouldExitCurrentIteration) { - if (state.LowestBreakIteration < i) - return; - } + var result = Parallel.For(1, 101, (i, state) => + { + Console.WriteLine($"Beginning iteration {i}"); + int delay; + lock (rnd) + delay = rnd.Next(1, 1001); + Thread.Sleep(delay); - if (i == breakIndex) { - Console.WriteLine("Break in iteration {0}", i); - state.Break(); - if (state.LowestBreakIteration.HasValue) - if (lowest < state.LowestBreakIteration) - lowest = state.LowestBreakIteration; - else - lowest = state.LowestBreakIteration; - } + if (state.ShouldExitCurrentIteration) + { + if (state.LowestBreakIteration < i) + return; + } - Console.WriteLine("Completed iteration {0}", i); - }); - if (lowest.HasValue) - Console.WriteLine("\nLowest Break Iteration: {0}", lowest); - else - Console.WriteLine("\nNo lowest break iteration."); - } + if (i == breakIndex) + { + Console.WriteLine($"Break in iteration {i}"); + state.Break(); + } + + Console.WriteLine($"Completed iteration {i}"); + }); + + if (result.LowestBreakIteration.HasValue) + Console.WriteLine($"\nLowest Break Iteration: {result.LowestBreakIteration}"); + else + Console.WriteLine($"\nNo lowest break iteration."); + } } // The example displays output like the following: // Will call Break at iteration 8