-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProgram.cs
111 lines (98 loc) · 3.33 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
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
105
106
107
108
109
110
111
using Microsoft.Extensions.DependencyInjection;
namespace ErrorHandling
{
class Program
{
private readonly IHttpClientFactory clientFactory;
private Program()
{
var services = new ServiceCollection();
services.AddHttpClient();
this.clientFactory = services.BuildServiceProvider().GetRequiredService<IHttpClientFactory>();
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
private static async Task<string> FindLongestLineAsync(
string url, IHttpClientFactory cf)
{
using (HttpClient w = cf.CreateClient())
{
Stream body = await w.GetStreamAsync(url);
using (var bodyTextReader = new StreamReader(body))
{
string longestLine = string.Empty;
while (!bodyTextReader.EndOfStream)
{
string? line = await bodyTextReader.ReadLineAsync();
if (line is not null && line.Length > longestLine.Length)
{
longestLine = line;
}
}
return longestLine;
}
}
}
private async Task HandleExceptions()
{
try
{
string longest = await FindLongestLineAsync(
"http://192.168.22.1/", this.clientFactory);
Console.WriteLine($"Longest line: {longest}");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error fetching page: {ex.Message}");
}
}
class PotentiallySurprising
{
public async Task<string> FindLongestLineAsync(string url)
{
ArgumentNullException.ThrowIfNull(url);
await Task.Yield();
return "";
}
}
class ThrowImmediately
{
public static Task<string> FindLongestLineAsync(string url)
{
ArgumentNullException.ThrowIfNull(url);
return FindLongestLineCore(url);
static async Task<string> FindLongestLineCore(string url)
{
return await Program.FindLongestLineAsync(url, new Program().clientFactory);
}
}
}
static async Task CatchAll(Task[] ts)
{
try
{
var t = Task.WhenAll(ts);
await t.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
t.Wait();
}
catch (AggregateException all)
{
Console.WriteLine(all);
}
}
static async Task GetSeveral(IHttpClientFactory cf)
{
using (HttpClient w = cf.CreateClient())
{
w.MaxResponseContentBufferSize = 2_000_000;
Task<string> g1 = w.GetStringAsync("https://endjin.com/");
Task<string> g2 = w.GetStringAsync("https://oreilly.com");
// BAD!
Console.WriteLine((await g1).Length);
Console.WriteLine((await g2).Length);
}
}
}
}