-
Notifications
You must be signed in to change notification settings - Fork 8
/
AsyncCoroutineDemoMutual.cs
85 lines (70 loc) · 2.5 KB
/
AsyncCoroutineDemoMutual.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
83
84
85
// https://github.com/noseratio/coroutines-talk
#nullable enable
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Coroutines
{
public static class AsyncCoroutineDemoMutual
{
private static async IAsyncEnumerable<int> CoroutineA(
IAsyncCoroutineProxy<int> coroutineProxy,
[EnumeratorCancellation] CancellationToken token)
{
var coroutineB = await coroutineProxy.AsAsyncEnumerable(token);
// await for coroutineB to advance by 40 steps
await foreach (var step in coroutineB)
{
if (step >= 40)
break;
}
var inputIdler = new InputIdler();
var interval = new Interval();
for (int i = 0; i < 80; i++)
{
await inputIdler.Yield(token);
Console.SetCursorPosition(0, 0);
Console.Write($"{nameof(CoroutineA)}: {new String('A', i)}");
await interval.Delay(25, token);
yield return i;
}
}
/// <summary>
/// CoroutineB yields to CoroutineA
/// </summary>
private static async IAsyncEnumerable<int> CoroutineB(
[EnumeratorCancellation] CancellationToken token)
{
var inputIdler = new InputIdler();
var interval = new Interval();
for (int i = 0; i < 80; i++)
{
await inputIdler.Yield(token);
Console.SetCursorPosition(0, 1);
Console.Write($"{nameof(CoroutineB)}: {new String('B', i)}");
await interval.Delay(50, token);
yield return i;
}
}
public static async ValueTask DemoAsync(CancellationToken token)
{
while (true)
{
token.ThrowIfCancellationRequested();
Console.Clear();
await RunCoroutinesAsync(token);
}
}
private static async ValueTask RunCoroutinesAsync(CancellationToken token)
{
var proxyA = new AsyncCoroutineProxy<int>();
var proxyB = new AsyncCoroutineProxy<int>();
// start both coroutines
await Task.WhenAll(
proxyA.RunAsync(token => CoroutineA(proxyB, token), token),
proxyB.RunAsync(token => CoroutineB(token), token));
}
}
}