-
Notifications
You must be signed in to change notification settings - Fork 8
/
LoopWindow.xaml.cs
104 lines (90 loc) · 3.2 KB
/
LoopWindow.xaml.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.IO;
using System.Net.Http;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
namespace AsyncAwait;
/// <summary>
/// Interaction logic for LoopWindow.xaml
/// </summary>
public partial class LoopWindow : Window
{
private readonly IHttpClientFactory clientFactory;
public LoopWindow()
{
InitializeComponent();
var services = new ServiceCollection();
services.AddHttpClient();
this.clientFactory = services.BuildServiceProvider().GetRequiredService<IHttpClientFactory>();
}
private void fetchButton_Click(object sender, RoutedEventArgs e)
{
FetchAndShowBody(urlTextBox.Text, this.clientFactory);
}
// Example 11 shows this alternative
#if false
private async Task FetchAndShowBody(string url, IHttpClientFactory cf)
#endif
private async void FetchAndShowBody(string url, IHttpClientFactory cf)
{
using (HttpClient w = cf.CreateClient())
{
Stream body = await w.GetStreamAsync(url);
using (var bodyTextReader = new StreamReader(body))
{
while (!bodyTextReader.EndOfStream)
{
string? line = await bodyTextReader.ReadLineAsync();
bodyTextBox.AppendText(line);
bodyTextBox.AppendText(Environment.NewLine);
await Task.Delay(TimeSpan.FromMilliseconds(10));
}
}
}
}
private void IncompleteOldSchoolFetchAndShowBody(
string url, IHttpClientFactory cf)
{
HttpClient w = cf.CreateClient();
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
w.GetStreamAsync(url).ContinueWith(getStreamTask =>
{
Stream body = getStreamTask.Result;
var bodyTextReader = new StreamReader(body);
StartNextIteration();
void StartNextIteration()
{
if (!bodyTextReader.EndOfStream)
{
bodyTextReader.ReadLineAsync().ContinueWith(readLineTask =>
{
string? line = readLineTask.Result;
bodyTextBox.AppendText(line);
bodyTextBox.AppendText(Environment.NewLine);
Task.Delay(TimeSpan.FromMilliseconds(10))
.ContinueWith(
_ => StartNextIteration(), uiScheduler);
},
uiScheduler);
}
};
},
uiScheduler);
}
public static async Task<string?> GetServerHeaderAsync(
string url, IHttpClientFactory cf)
{
using (HttpClient w = cf.CreateClient())
{
var request = new HttpRequestMessage(HttpMethod.Head, url);
HttpResponseMessage response = await w.SendAsync(
request, HttpCompletionOption.ResponseHeadersRead);
string? result = null;
IEnumerable<string>? values;
if (response.Headers.TryGetValues("Server", out values))
{
result = values.FirstOrDefault();
}
return result;
}
}
}