-
Notifications
You must be signed in to change notification settings - Fork 8
/
MainWindow.xaml.cs
73 lines (62 loc) · 2.18 KB
/
MainWindow.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
using System.Diagnostics;
using System.Net.Http;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
namespace AsyncAwait;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly IHttpClientFactory clientFactory;
public MainWindow()
{
InitializeComponent();
var services = new ServiceCollection();
services.AddHttpClient();
this.clientFactory = services.BuildServiceProvider().GetRequiredService<IHttpClientFactory>();
okButton.Click += async (s, e) =>
{
using (HttpClient w = this.clientFactory.CreateClient())
{
infoTextBlock.Text = await w.GetStringAsync(uriTextBox.Text);
}
};
}
private void fetchHeadersButton_Click(object sender, RoutedEventArgs e)
{
FetchAndShowHeaders("https://endjin.com/", this.clientFactory);
Debug.WriteLine("Method returned");
}
// Note: as you'll see later, async methods usually should not be void
private async void FetchAndShowHeaders(string url, IHttpClientFactory cf)
{
using (HttpClient w = cf.CreateClient())
{
var req = new HttpRequestMessage(HttpMethod.Head, url);
HttpResponseMessage response =
await w.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
headerListTextBox.Text = response.Headers.ToString();
}
}
private void OldSchoolFetchHeaders(string url, IHttpClientFactory cf)
{
HttpClient w = cf.CreateClient();
var req = new HttpRequestMessage(HttpMethod.Head, url);
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
w.SendAsync(req, HttpCompletionOption.ResponseHeadersRead)
.ContinueWith(sendTask =>
{
try
{
HttpResponseMessage response = sendTask.Result;
headerListTextBox.Text = response.Headers.ToString();
}
finally
{
w.Dispose();
}
},
uiScheduler);
}
}