-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathProgram.cs
100 lines (84 loc) · 2.5 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
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace PostSharp.Samples.AutoRetry
{
internal static class Program
{
private const double failureRate = 0.1;
private static readonly Random random = new Random();
private static readonly Stopwatch stopwatch = Stopwatch.StartNew();
private static void Main(string[] args)
{
try
{
DownloadFile(
"https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/pineisland_oli_2017026_lrg-crop.jpg");
}
catch
{
Console.WriteLine("DownloadFile failed!");
}
try
{
DownloadFileAsync(
"https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/pineisland_oli_2017026_lrg-crop.jpg")
.Wait();
}
catch
{
Console.WriteLine("DownloadFileAsync failed!");
}
}
[AutoRetry(MaxRetries = 3)]
private static void DownloadFile(string url)
{
WriteMessage("Attempting to download the file.");
var webClient = new WebClient();
var buffer = new byte[16 * 1024];
using (var stream = webClient.OpenRead(url))
{
int countRead;
while ((countRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
// Simulate a network failure.
if (random.NextDouble() < failureRate)
{
WriteMessage("Network failure.");
throw new WebException();
}
}
}
// Simulate success.
WriteMessage("Success!");
}
[AutoRetry(MaxRetries = 3)]
private static async Task DownloadFileAsync(string url)
{
WriteMessage("Attempting to download the file.");
var webClient = new WebClient();
var buffer = new byte[16 * 1024];
using (var stream = webClient.OpenRead(url))
{
int countRead;
while ((countRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
// Simulate a network failure.
if (random.NextDouble() < failureRate)
{
WriteMessage("Network failure.");
throw new WebException();
}
}
}
// Simulate success.
WriteMessage("Success!");
}
// Writes a message to the console with a timestamp.
private static void WriteMessage(string message)
{
Console.WriteLine("{0} ms - {1}", stopwatch.ElapsedMilliseconds, message);
}
}
}