|
1 |
| -// <Snippet2> |
| 1 | +// <Snippet2> |
2 | 2 | using System;
|
3 | 3 | using System.Threading;
|
4 | 4 | using System.Threading.Tasks;
|
5 | 5 |
|
6 | 6 | public class Example
|
7 | 7 | {
|
8 |
| - public static void Main() |
9 |
| - { |
10 |
| - var rnd = new Random(); |
11 |
| - int breakIndex = rnd.Next(1, 11); |
12 |
| - Nullable<long> lowest = new Nullable<long>(); |
| 8 | + public static void Main() |
| 9 | + { |
| 10 | + var rnd = new Random(); |
| 11 | + int breakIndex = rnd.Next(1, 11); |
13 | 12 |
|
14 |
| - Console.WriteLine("Will call Break at iteration {0}\n", |
15 |
| - breakIndex); |
| 13 | + Console.WriteLine($"Will call Break at iteration {breakIndex}\n"); |
16 | 14 |
|
17 |
| - var result = Parallel.For(1, 101, (i, state) => { |
18 |
| - Console.WriteLine("Beginning iteration {0}", i); |
19 |
| - int delay; |
20 |
| - Monitor.Enter(rnd); |
21 |
| - delay = rnd.Next(1, 1001); |
22 |
| - Monitor.Exit(rnd); |
23 |
| - Thread.Sleep(delay); |
24 |
| - |
25 |
| - if (state.ShouldExitCurrentIteration) { |
26 |
| - if (state.LowestBreakIteration < i) |
27 |
| - return; |
28 |
| - } |
| 15 | + var result = Parallel.For(1, 101, (i, state) => |
| 16 | + { |
| 17 | + Console.WriteLine($"Beginning iteration {i}"); |
| 18 | + int delay; |
| 19 | + lock (rnd) |
| 20 | + delay = rnd.Next(1, 1001); |
| 21 | + Thread.Sleep(delay); |
29 | 22 |
|
30 |
| - if (i == breakIndex) { |
31 |
| - Console.WriteLine("Break in iteration {0}", i); |
32 |
| - state.Break(); |
33 |
| - if (state.LowestBreakIteration.HasValue) |
34 |
| - if (lowest < state.LowestBreakIteration) |
35 |
| - lowest = state.LowestBreakIteration; |
36 |
| - else |
37 |
| - lowest = state.LowestBreakIteration; |
38 |
| - } |
| 23 | + if (state.ShouldExitCurrentIteration) |
| 24 | + { |
| 25 | + if (state.LowestBreakIteration < i) |
| 26 | + return; |
| 27 | + } |
39 | 28 |
|
40 |
| - Console.WriteLine("Completed iteration {0}", i); |
41 |
| - }); |
42 |
| - if (lowest.HasValue) |
43 |
| - Console.WriteLine("\nLowest Break Iteration: {0}", lowest); |
44 |
| - else |
45 |
| - Console.WriteLine("\nNo lowest break iteration."); |
46 |
| - } |
| 29 | + if (i == breakIndex) |
| 30 | + { |
| 31 | + Console.WriteLine($"Break in iteration {i}"); |
| 32 | + state.Break(); |
| 33 | + } |
| 34 | + |
| 35 | + Console.WriteLine($"Completed iteration {i}"); |
| 36 | + }); |
| 37 | + |
| 38 | + if (result.LowestBreakIteration.HasValue) |
| 39 | + Console.WriteLine($"\nLowest Break Iteration: {result.LowestBreakIteration}"); |
| 40 | + else |
| 41 | + Console.WriteLine($"\nNo lowest break iteration."); |
| 42 | + } |
47 | 43 | }
|
48 | 44 | // The example displays output like the following:
|
49 | 45 | // Will call Break at iteration 8
|
|
0 commit comments