-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCustomAsyncEnumerable.cs
62 lines (52 loc) · 1.81 KB
/
CustomAsyncEnumerable.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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class CustomAsyncEnumerable : IRunnable
{
public async Task Run()
{
using var yetAnotherTokenSource = new CancellationTokenSource();
var custom = new CustomEnumerable(yetAnotherTokenSource);
await foreach (var delay in custom
.WithCancellation(yetAnotherTokenSource.Token)
.ConfigureAwait(false))
{
Console.WriteLine($"await Task.Delay({delay})");
await Task.Delay(delay)
.ConfigureAwait(false);
}
custom = new CustomEnumerable(yetAnotherTokenSource);
await foreach (var delay in custom)
{
Console.WriteLine($"await Task.Delay({delay})");
await Task.Delay(delay)
.ConfigureAwait(false);
}
}
class CustomEnumerable : IAsyncEnumerable<int>, IAsyncEnumerator<int>
{
int called = 0;
private readonly CancellationTokenSource tokenSource;
public CustomEnumerable(CancellationTokenSource tokenSource)
{
this.tokenSource = tokenSource;
}
public int Current => 1;
public ValueTask DisposeAsync()
{
return new ValueTask();
}
public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
Console.WriteLine($"Is token passed to WithCancellation? {this.tokenSource.Token == cancellationToken}");
return this;
}
public ValueTask<bool> MoveNextAsync()
{
if (called++ == 1)
return new ValueTask<bool>(true);
return new ValueTask<bool>(false);
}
}
}