|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.Extensions.Hosting; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace HttpClientDemo |
| 10 | +{ |
| 11 | + public class Worker : BackgroundService |
| 12 | + { |
| 13 | + private readonly ILogger<Worker> logger; |
| 14 | + |
| 15 | + public Worker(ILogger<Worker> logger) |
| 16 | + { |
| 17 | + this.logger = logger; |
| 18 | + } |
| 19 | + |
| 20 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 21 | + { |
| 22 | + while (!stoppingToken.IsCancellationRequested) |
| 23 | + { |
| 24 | + this.logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); |
| 25 | + |
| 26 | + try |
| 27 | + { |
| 28 | + await Task.WhenAll(Enumerable.Range(0, 250).Select(_ => GetData(stoppingToken))); |
| 29 | + } |
| 30 | + catch (Exception ex) |
| 31 | + { |
| 32 | + this.logger.LogError(ex, "Worker failed at: {time}", DateTimeOffset.Now); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private async Task GetData(CancellationToken stoppingToken) |
| 38 | + { |
| 39 | + using (var httpClient = GetHttpClient()) |
| 40 | + { |
| 41 | + try |
| 42 | + { |
| 43 | + var response = await httpClient.GetAsync("http://bing.com/", stoppingToken); |
| 44 | + this.logger.LogDebug("{StatusCode}", response.StatusCode); |
| 45 | + } |
| 46 | + catch (Exception ex) |
| 47 | + { |
| 48 | + this.logger.LogError("{ExceptionType}: {ExceptionMessage}", ex.GetType().Name, ex.Message); |
| 49 | + |
| 50 | + if (!(ex.InnerException is null)) |
| 51 | + { |
| 52 | + this.logger.LogError("{InnerExceptionType}: {InnerExceptionMessage}", ex.InnerException.GetType().Name, ex.InnerException.Message); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private HttpClient GetHttpClient() |
| 59 | + { |
| 60 | + var httpClient = new HttpClient(); |
| 61 | + return httpClient; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments