-
Notifications
You must be signed in to change notification settings - Fork 8
/
AsyncCoroutineDemo.cs
82 lines (71 loc) · 2.63 KB
/
AsyncCoroutineDemo.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
81
82
// https://github.com/noseratio/coroutines-talk
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Coroutines
{
public static class AsyncCoroutineDemo
{
private static async IAsyncEnumerable<int> CoroutineA(
[EnumeratorCancellation] CancellationToken token)
{
var inputIdler = new InputIdler();
for (int i = 0; i < 80; i++)
{
// yield to the event loop to process any keyboard/mouse input first
await inputIdler.Yield(token);
// now we could use Task.Run for this
// but let's pretend this code must execute on the UI thread
Console.SetCursorPosition(0, 0);
Console.Write($"{nameof(CoroutineA)}: {new String('A', i)}");
yield return i;
}
}
private static async IAsyncEnumerable<int> CoroutineB(
[EnumeratorCancellation] CancellationToken token)
{
var inputIdler = new InputIdler();
for (int i = 0; i < 80; i++)
{
// yield to the event loop to process any keyboard/mouse input first
await inputIdler.Yield(token);
Console.SetCursorPosition(0, 1);
Console.Write($"{nameof(CoroutineB)}: {new String('B', i)}");
// slow down CoroutineB
await Task.Delay(25, token);
yield return i;
}
}
private static async Task DriveCoroutinesAsync<T>(
int intervalMs,
CancellationToken token,
params Func<CancellationToken, IAsyncEnumerable<T>>[] coroutines)
{
var tasks = coroutines.Select(async coroutine =>
{
var interval = new Interval();
await foreach (var item in coroutine(token).WithCancellation(token))
{
await interval.Delay(intervalMs, token);
}
});
await Task.WhenAll(tasks);
}
public static async Task DemoAsync(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
Console.Clear();
await DriveCoroutinesAsync<int>(
intervalMs: 50,
token,
CoroutineA, CoroutineB);
}
}
}
}