HttpClient and request lifetime
HttpClient and request lifetime
HttpClient sends HTTP requests through a message handler. A real SocketsHttpHandler maintains a connection pool, so repeatedly constructing and disposing clients with separate handlers can cause unnecessary connection churn. Use a long-lived client with a suitable PooledConnectionLifetime, or factory-created clients with managed handler lifetimes. A request and its response have shorter ownership boundaries: dispose them after processing. With ResponseHeadersRead, HttpClient.Timeout covers the operation only through the response headers; use a separately propagated deadline and a byte limit for reading the body. The Content-Length header alone is not a trusted byte limit. Construct a fresh request for each attempt; never blindly retry a non-idempotent operation. Factory-created clients are intended to be short-lived; avoid capturing typed clients in singletons. IHttpClientFactory is a dependency injection integration, not a requirement for using HttpClient. All examples here inject a fake handler; no DNS, TLS or HTTP traffic occurs.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Reuse a client for two requests
A fake handler echoes the absolute path. Relative request paths combine with the base address.
using System;using System.Net;using System.Net.Http;using System.Threading;using System.Threading.Tasks;using var client = new HttpClient(new EchoHandler()){ BaseAddress = new Uri("https://example.test/") };foreach (string path in new[] { "catalog", "help" }){ using var request = new HttpRequestMessage(HttpMethod.Get, path); using var response = await client.SendAsync(request); Console.WriteLine(await response.Content.ReadAsStringAsync());}sealed class EchoHandler : HttpMessageHandler{ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { token.ThrowIfCancellationRequested(); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(request.RequestUri!.AbsolutePath) }); }}The same client sends both requests, but each request and response is independently disposed. A fake handler does not demonstrate physical connection reuse.
Expected observation (reasoned, not executed):
/catalog/helpConfigure a pool lifetime without sending traffic
A finite lifetime lets future connections use fresh DNS resolution when old connections are retired. It is not a DNS polling timer.
using System;using System.Net.Http;using var handler = new SocketsHttpHandler{ PooledConnectionLifetime = TimeSpan.FromMinutes(2), MaxConnectionsPerServer = 8};using var client = new HttpClient(handler, disposeHandler: false);Console.WriteLine(handler.PooledConnectionLifetime.TotalSeconds);Console.WriteLine(handler.MaxConnectionsPerServer);These are illustrative settings, not measured recommendations. The caller owns the handler because disposeHandler is false. No request is made.
Expected observation (reasoned, not executed):
1208Read a bounded response stream
ResponseHeadersRead permits processing the body separately. This fixture has a known five-byte body; pass a token to body reads too.
using System;using System.IO;using System.Net;using System.Net.Http;using System.Text;using System.Threading;using System.Threading.Tasks;using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(5));using var client = new HttpClient(new SmallHandler());using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.test/data");using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token);response.EnsureSuccessStatusCode();await using Stream body = await response.Content.ReadAsStreamAsync(deadline.Token);byte[] bytes = new byte[5];await body.ReadExactlyAsync(bytes, deadline.Token);Console.WriteLine(Encoding.UTF8.GetString(bytes));sealed class SmallHandler : HttpMessageHandler{ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { token.ThrowIfCancellationRequested(); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent("ready"u8.ToArray()) }); }}The fixture reads a known length, not an arbitrary untrusted body. For a live response enforce a size limit while reading; do not rely solely on Content-Length. With ResponseHeadersRead, HttpClient.Timeout does not cover subsequent body reads.
Expected observation (reasoned, not executed):
readyCommon mistakes and design limits
An HttpRequestMessage should not be sent twice; retries require a fresh request and replayable content. Do not mutate shared default headers while concurrent requests are in progress. For factory clients, keep typed clients short-lived; capturing one in a singleton can defeat handler rotation. Pooled handlers can share cookies, so review cookie isolation. Never disable certificate validation to make a connection succeed. A cancellation or timeout does not prove that the server did not process a request.
Apply the concept
Design a client for a catalog service: 50 calls per minute, per-request deadlines, and DNS changes. Describe client, handler, request, response and stream lifetimes.
Check your work: Use a long-lived handler/client with a deliberately selected connection lifetime, or a factory-managed handler. Each call creates/disposes its request and response, reads a bounded body using its deadline, and reports cancellation separately. Retire the shared client only when its owner shuts down.
Further study
Continue with the next planned lesson. Consult the official documentation for API contracts: httpguidelines, factory, completionoption, readexactly. API and runtime verification remain incomplete.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HttpClient and request lifetime — knowledge check
Apply the lesson concepts to the following scenarios.
Why reuse an HttpClient with its handler?
What does PooledConnectionLifetime control?
What does ResponseHeadersRead change?
Who disposes a response?
What does a fake HttpMessageHandler test?