Skip to content

Commit c9a596e

Browse files
committed
Single use HttpClient
1 parent 53bf978 commit c9a596e

7 files changed

+150
-0
lines changed

HttpClientFactoryDemo.sln

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.30403.11
5+
MinimumVisualStudioVersion = 15.0.26124.0
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HttpClientFactoryDemo", "HttpClientFactoryDemo\HttpClientFactoryDemo.csproj", "{FF8724C6-05D5-42FD-BCEA-2347C8D0612F}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{FF8724C6-05D5-42FD-BCEA-2347C8D0612F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{FF8724C6-05D5-42FD-BCEA-2347C8D0612F}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{FF8724C6-05D5-42FD-BCEA-2347C8D0612F}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{FF8724C6-05D5-42FD-BCEA-2347C8D0612F}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {5FC435FF-34F9-4FC5-8FA1-DF3168700212}
24+
EndGlobalSection
25+
EndGlobal
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Worker">
2+
3+
<PropertyGroup>
4+
<TargetFrameworks>netcoreapp3.1;netcoreapp2.1;net5.0</TargetFrameworks>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.6" />
9+
<PackageReference Include="System.Net.Http" Version="4.3.4" Condition="'$(TargetFramework)' == 'net48'" />
10+
</ItemGroup>
11+
</Project>

HttpClientFactoryDemo/Program.cs

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Hosting;
7+
8+
namespace HttpClientDemo
9+
{
10+
public static class Program
11+
{
12+
public static async Task Main(string[] args)
13+
{
14+
await Host.CreateDefaultBuilder(args)
15+
.ConfigureServices((hostContext, services) =>
16+
{
17+
services.AddHostedService<Worker>();
18+
})
19+
.RunConsoleAsync();
20+
}
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"profiles": {
3+
"HttpClientDemo": {
4+
"commandName": "Project",
5+
"environmentVariables": {
6+
"DOTNET_ENVIRONMENT": "Development"
7+
}
8+
}
9+
}
10+
}

HttpClientFactoryDemo/Worker.cs

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft": "Warning",
6+
"Microsoft.Hosting.Lifetime": "Information"
7+
}
8+
}
9+
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft": "Warning",
6+
"Microsoft.Hosting.Lifetime": "Information"
7+
}
8+
}
9+
}

0 commit comments

Comments
 (0)