Skip to content

Commit 86ab733

Browse files
committed
Use a single HttpClient to optimize connections
Per dotnet/aspnetcore#28385 (comment), you should almost always use a single pooled HttpClient instance instead of disposing them as they're used.
1 parent 8c81b4c commit 86ab733

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

Microsoft.NET.Build.Containers/Registry.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public record struct Registry(Uri BaseUri)
1919

2020
public async Task<Image> GetImageManifest(string name, string reference)
2121
{
22-
using HttpClient client = GetClient();
22+
HttpClient client = GetClient();
2323

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

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

7171
// No local copy, so download one
7272

73-
using HttpClient client = GetClient();
73+
HttpClient client = GetClient();
7474

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

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

102102
private readonly async Task UploadBlob(string name, string digest, Stream contents)
103103
{
104-
using HttpClient client = GetClient();
104+
HttpClient client = GetClient();
105105

106106
if (await BlobAlreadyUploaded(name, digest, client))
107107
{
@@ -155,7 +155,14 @@ private readonly async Task<bool> BlobAlreadyUploaded(string name, string digest
155155
return false;
156156
}
157157

158+
private static HttpClient _client = CreateClient();
159+
158160
private static HttpClient GetClient()
161+
{
162+
return _client;
163+
}
164+
165+
private static HttpClient CreateClient()
159166
{
160167
var clientHandler = new AuthHandshakeMessageHandler(new HttpClientHandler() { UseDefaultCredentials = true });
161168
HttpClient client = new(clientHandler);
@@ -177,7 +184,7 @@ public async Task Push(Image x, string name, string? tag, string baseName, Actio
177184
{
178185
tag ??= "latest";
179186

180-
using HttpClient client = GetClient();
187+
HttpClient client = GetClient();
181188
var reg = this;
182189
await Task.WhenAll(x.LayerDescriptors.Select(async descriptor => {
183190
string digest = descriptor.Digest;

0 commit comments

Comments
 (0)