-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
60 lines (55 loc) · 1.92 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
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace AsynchronousStreams
{
/// <summary>
/// Async Streams
/// https://blog.jetbrains.com/dotnet/2019/09/16/async-streams-look-new-language-features-c-8/
/// https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/generate-consume-asynchronous-stream
/// </summary>
class Program
{
static async Task Main(string[] args)
{
//await AsynchronousStreamsWithCancellationToken();
await PrintSequence();
}
static async IAsyncEnumerable<int> GenerateSequence()
{
foreach (var item in Enumerable.Range(0, 100))
{
await Task.Delay(100);
yield return item;
}
}
static async Task PrintSequence()
{
await foreach (var number in GenerateSequence())
{
Console.WriteLine(number);
}
}
static async Task AsynchronousStreamsWithCancellationToken()
{
var cancellationToken = new CancellationTokenSource(millisecondsDelay: 1000);
await foreach (var result in GetTopSearchResults("dotnet").WithCancellation(cancellationToken.Token))
{
Console.WriteLine(result);
}
}
static async IAsyncEnumerable<string> GetTopSearchResults(string term, [EnumeratorCancellation]CancellationToken token = default)
{
while (!token.IsCancellationRequested)
{
using var client = new HttpClient();
yield return await client.GetStringAsync($"https://www.google.com?q={term}");
yield return await client.GetStringAsync($"https://www.bing.com?q={term}");
}
}
}
}