-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallelForCancellation.cs
More file actions
76 lines (69 loc) · 3.13 KB
/
ParallelForCancellation.cs
File metadata and controls
76 lines (69 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ComputePi
{
public class ParallelForCancellation
{
// Demonstrated features:
// CancellationTokenSource
// Parallel.For()
// ParallelOptions
// ParallelLoopResult
// Expected results:
// An iteration for each argument value (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) is executed.
// The order of execution of the iterations is undefined.
// The iteration when i=2 cancels the loop.
// Some iterations may bail out or not start at all; because they are temporally executed in unpredictable order,
// it is impossible to say which will start/complete and which won't.
// At the end, an OperationCancelledException is surfaced.
// Documentation:
// http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource(VS.100).aspx
public void CancelDemo()
{
CancellationTokenSource cancellationSource = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cancellationSource.Token;
try
{
ParallelLoopResult loopResult = Parallel.For(
0,
10,
options,
(i, loopState) =>
{
Console.WriteLine("Start Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
// Simulate a cancellation of the loop when i=5
if (i == 5)
{
cancellationSource.Cancel();
}
// Simulates a long execution
for (int j = 0; j < 10; j++)
{
Thread.Sleep(1 * 200);
// check to see whether or not to continue
if (loopState.ShouldExitCurrentIteration) return;
}
Console.WriteLine("Finish Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
}
);
if (loopResult.IsCompleted)
{
Console.WriteLine("All iterations completed successfully. THIS WAS NOT EXPECTED.\n");
}
}
// No exception is expected in this example, but if one is still thrown from a task,
// it will be wrapped in AggregateException and propagated to the main thread.
catch (AggregateException e)
{
Console.WriteLine("Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{0}\n", e);
}
// Catching the cancellation exception
catch (OperationCanceledException e)
{
Console.WriteLine("An iteration has triggered a cancellation. THIS WAS EXPECTED.\n{0}\n", e.ToString());
}
}
}
}