-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
72 lines (57 loc) · 1.62 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace system_linq_async
{
class Program
{
static async Task Main()
{
var timeA = await Measure(A);
var timeB = await Measure(B);
Console.WriteLine($"A took {timeA}");
Console.WriteLine($"B took {timeB}");
Console.WriteLine("DONE");
}
static async Task A()
{
// Enumerates one by one
await foreach (var number in ProduceNumbersAsync())
{
Console.WriteLine($"{number}");
}
Console.WriteLine("A DONE");
}
static async Task B()
{
// Waits until all are enumerated
foreach (var number in await ProduceNumbersAsync().ToListAsync())
{
Console.WriteLine($"{number}");
}
Console.WriteLine("B DONE");
}
static async Task<TimeSpan> Measure(Func<Task> func)
{
var stopWatch = Stopwatch.StartNew();
await func();
stopWatch.Stop();
return stopWatch.Elapsed;
}
static async IAsyncEnumerable<int> ProduceNumbersAsync()
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(10);
yield return i;
}
}
// Pros:
// More concise, closer to synchronous
// yield as a keyword, not as a type
// Cons:
// No ParallelAsync
}
}