-
Notifications
You must be signed in to change notification settings - Fork 1
/
_HandlingException.cs
75 lines (65 loc) · 2.36 KB
/
_HandlingException.cs
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
using Common.Interfaces;
using System;
using System.Diagnostics;
using System.Linq;
namespace Ch04.Examples
{
public class _HandlingException : IBaseExecutor
{
private readonly ParallelQuery<int> ParallelQueryRange = ParallelEnumerable.Range(1, 500);
public void Run()
{
//PropagateBackToTheCaller();
DelegateHandle();
}
private void DelegateHandle()
{
Func<int, int> SelectDivision = (i) =>
{
try
{
return i / (i - 10);
}
catch (Exception ex)
{
Console.WriteLine(@$"{Environment.NewLine}Type Exception: {ex.GetType().Name} | Message: {ex.Message} | StackTrace: {ex.StackTrace} |");
return -1;
}
};
Stopwatch watch = null;
ParallelQuery<int> query = ParallelQueryRange.Select(i => SelectDivision(i)).WithDegreeOfParallelism(2);
watch = Stopwatch.StartNew();
try
{
query.ForAll(item => Console.Write($"{item}:{watch.ElapsedMilliseconds} |"));
}
catch (AggregateException aggregateException)
{
foreach (var ex in aggregateException.InnerExceptions)
{
Console.WriteLine(ex.Message);
if (ex is DivideByZeroException)
Console.WriteLine("Attempt to divide by zero. Query stopped.");
}
}
Console.WriteLine($"{Environment.NewLine}Full Result returned in { watch.ElapsedMilliseconds} ms{Environment.NewLine}");
}
private void PropagateBackToTheCaller()
{
ParallelQuery<int> query = ParallelQueryRange.Select(i => i / (i - 10)).WithDegreeOfParallelism(2);
try
{
query.ForAll(i => Console.WriteLine(i));
}
catch (AggregateException aggregateException)
{
foreach (var ex in aggregateException.InnerExceptions)
{
Console.WriteLine(ex.Message);
if (ex is DivideByZeroException)
Console.WriteLine("Attempt to divide by zero. Query stopped.");
}
}
}
}
}