-
Notifications
You must be signed in to change notification settings - Fork 0
/
01_IOBoundvsCpuBoundTask.cs
80 lines (64 loc) · 1.95 KB
/
01_IOBoundvsCpuBoundTask.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
76
77
78
79
80
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using AsyncLab.Support;
namespace AsyncLab
{
//[DoNotRun]
public class IOBoundVsCpuBoundTask
{
readonly IOutput output;
public IOBoundVsCpuBoundTask(IOutput output)
{
this.output = output;
}
/**
[Run]
public async Task IOBound()
{
// On IO task you can only await
var weatherUrl = "http://wttr.in/~everest?format=3";
}
/**
[Run]
public void CpuBound()
{
// This is blocking the calling thread. Is it a problem?
// It depends on the caller...
var result = FindPrimeNumbers(100, 10000000);
output.Log("I'm blocked, I've to wait for FindPrimeNumbers() to finish...");
output.Log($"Found {result.Length} prime numbers");
}
/**
[Run]
public void IOBoundDoneWrong()
{
// Stop stealing threads from the ThreadPool!
// You're even paying a context switch
}
/**/
int[] FindPrimeNumbers(int begin, int end)
{
output.Log("FindPrimeNumber is running");
IList<int> primeNumbers = new List<int>();
for (int i = begin; i <= end; i++)
{
if (IsPrime(i)) primeNumbers.Add(i);
}
return primeNumbers.ToArray();
}
static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int) Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
}
}