Skip to content

Commit 554a385

Browse files
Merge pull request #234 from rainersigwald/shared-httpclient
Long-lived HttpClient
2 parents d774d17 + 3c2cae5 commit 554a385

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

Microsoft.NET.Build.Containers/Registry.cs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public record struct Registry(Uri BaseUri)
2121

2222
public async Task<Image> GetImageManifest(string name, string reference)
2323
{
24-
using HttpClient client = GetClient();
24+
HttpClient client = GetClient();
2525

2626
var response = await client.GetAsync(new Uri(BaseUri, $"/v2/{name}/manifests/{reference}"));
2727

@@ -72,7 +72,7 @@ public async Task<string> DownloadBlob(string name, Descriptor descriptor)
7272

7373
// No local copy, so download one
7474

75-
using HttpClient client = GetClient();
75+
HttpClient client = GetClient();
7676

7777
var response = await client.GetAsync(new Uri(BaseUri, $"/v2/{name}/blobs/{descriptor.Digest}"), HttpCompletionOption.ResponseHeadersRead);
7878

@@ -103,7 +103,7 @@ public async Task Push(Layer layer, string name, Action<string> logProgressMessa
103103

104104
private readonly async Task UploadBlob(string name, string digest, Stream contents)
105105
{
106-
using HttpClient client = GetClient();
106+
HttpClient client = GetClient();
107107

108108
if (await BlobAlreadyUploaded(name, digest, client))
109109
{
@@ -157,9 +157,16 @@ private readonly async Task<bool> BlobAlreadyUploaded(string name, string digest
157157
return false;
158158
}
159159

160+
private static HttpClient _client = CreateClient();
161+
160162
private static HttpClient GetClient()
161163
{
162-
var clientHandler = new AuthHandshakeMessageHandler(new HttpClientHandler() { UseDefaultCredentials = true });
164+
return _client;
165+
}
166+
167+
private static HttpClient CreateClient()
168+
{
169+
var clientHandler = new AuthHandshakeMessageHandler(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMilliseconds(10 /* total guess */) });
163170
HttpClient client = new(clientHandler);
164171

165172
client.DefaultRequestHeaders.Accept.Clear();
@@ -179,7 +186,7 @@ public async Task Push(Image x, string name, string? tag, string baseName, Actio
179186
{
180187
tag ??= "latest";
181188

182-
using HttpClient client = GetClient();
189+
HttpClient client = GetClient();
183190
var reg = this;
184191
await Task.WhenAll(x.LayerDescriptors.Select(async descriptor => {
185192
string digest = descriptor.Digest;

0 commit comments

Comments
 (0)