oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/csharp/async_tasks.txt
1.6 KiB, 1 run
created by r1870400018:11958, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Net.Http; |
| 4 | using System.Threading.Tasks; |
| 5 | |
| 6 | namespace Annealer.Examples |
| 7 | { |
| 8 | public class Fetcher |
| 9 | { |
| 10 | private readonly HttpClient _client = new(); |
| 11 | private readonly Dictionary<string, string> _cache = new(); |
| 12 | |
| 13 | public async Task<string> GetAsync(string url) |
| 14 | { |
| 15 | if (_cache.TryGetValue(url, out var cached)) |
| 16 | return cached; |
| 17 | |
| 18 | var response = await _client.GetAsync(url); |
| 19 | response.EnsureSuccessStatusCode(); |
| 20 | var body = await response.Content.ReadAsStringAsync(); |
| 21 | _cache[url] = body; |
| 22 | return body; |
| 23 | } |
| 24 | |
| 25 | public async Task<List<string>> GetAllAsync(IEnumerable<string> urls) |
| 26 | { |
| 27 | var tasks = new List<Task<string>>(); |
| 28 | foreach (var url in urls) |
| 29 | { |
| 30 | tasks.Add(GetAsync(url)); |
| 31 | } |
| 32 | var results = await Task.WhenAll(tasks); |
| 33 | return new List<string>(results); |
| 34 | } |
| 35 | |
| 36 | public async Task<string?> TryGetAsync(string url, int retries = 3) |
| 37 | { |
| 38 | for (int attempt = 1; attempt <= retries; attempt++) |
| 39 | { |
| 40 | try |
| 41 | { |
| 42 | return await GetAsync(url); |
| 43 | } |
| 44 | catch (HttpRequestException) |
| 45 | { |
| 46 | if (attempt == retries) |
| 47 | return null; |
| 48 | await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt))); |
| 49 | } |
| 50 | } |
| 51 | return null; |
| 52 | } |
| 53 | } |
| 54 | } |