HttpResponseMessage
Dispose
ReadAsStreamAsync
C#
.NET

Should you dispose HttpResponseMessage when using ReadAsStreamAsync?

Codemia Knowledge Hub ·

Yes, dispose HttpResponseMessage, but only after you have finished reading the stream from ReadAsStreamAsync. The response owns the underlying network stream, so disposing it first closes the connection and truncates or corrupts your data. Put the response and the stream in using scopes that end only after all reading is done.

Dispose after consuming the stream

csharp
1using System.Net.Http;
2using System.IO;
3using System.Threading.Tasks;
4
5public static async Task DownloadFileAsync(HttpClient client, string url, string outputPath)
6{
7    using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
8    response.EnsureSuccessStatusCode();
9
10    await using var contentStream = await response.Content.ReadAsStreamAsync();
11    await using var fileStream = File.Create(outputPath);
12
13    await contentStream.CopyToAsync(fileStream);
14    // Both streams and the response are disposed here, in reverse declaration order
15}

using var disposes when execution leaves the method. Declaration order matters because contentStream depends on response: response is declared first, so it is disposed last.

Why the response must be disposed

HttpResponseMessage holds resources tied to the HTTP connection:

  • The response content stream, which may be backed by a network socket
  • Response headers allocated during parsing
  • Internal buffers in the HTTP handler pipeline

Without disposal they stay allocated until the garbage collector finalizes the object, which may not happen promptly. In high-throughput code that leaks sockets:

csharp
1// This leaks responses - DO NOT do this in production
2public async Task<string> LeakyGetAsync(HttpClient client, string url)
3{
4    var response = await client.GetAsync(url);  // No using, no dispose
5    return await response.Content.ReadAsStringAsync();
6    // response is never disposed - socket may not be returned to the pool
7}
8
9// Correct version
10public async Task<string> ProperGetAsync(HttpClient client, string url)
11{
12    using var response = await client.GetAsync(url);
13    return await response.Content.ReadAsStringAsync();
14    // response disposed here, socket returned to pool
15}

Under load the leaky version eventually throws SocketException or HttpRequestException with "Only one usage of each socket address is normally permitted" because of port exhaustion.

Error paths count too. If EnsureSuccessStatusCode() throws, the response still has to be disposed: declare it with using before the status check, or dispose it in a catch block.

Disposing too early: returning the stream

The most common bug is disposing the response before the stream is consumed, which happens when a method returns the stream:

csharp
1// BROKEN: response disposed before stream is consumed
2public async Task<Stream> GetStreamBrokenAsync(HttpClient client, string url)
3{
4    using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
5    response.EnsureSuccessStatusCode();
6
7    return await response.Content.ReadAsStreamAsync();
8    // response is disposed HERE when the method returns
9    // The returned stream is now backed by a closed connection
10}
11
12// Caller gets a dead stream
13var stream = await GetStreamBrokenAsync(client, someUrl);
14await stream.CopyToAsync(output);  // Throws ObjectDisposedException or reads zero bytes

using var response disposes the response when the method returns. The caller's stream is backed by the response's network connection, which is now closed. ReadAsStreamAsync does not make an independent copy: the stream reads directly from the HTTP pipeline unless you explicitly buffer it.

Returning a stream safely

To hand a stream to the caller, transfer ownership of the response with it.

Wrap the response and stream together

csharp
1public sealed class HttpResponseStream : IAsyncDisposable
2{
3    private readonly HttpResponseMessage _response;
4    public Stream Stream { get; }
5
6    public HttpResponseStream(HttpResponseMessage response, Stream stream)
7    {
8        _response = response;
9        Stream = stream;
10    }
11
12    public async ValueTask DisposeAsync()
13    {
14        await Stream.DisposeAsync();
15        _response.Dispose();
16    }
17}
18
19// Usage
20public async Task<HttpResponseStream> GetStreamAsync(HttpClient client, string url)
21{
22    var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
23    try
24    {
25        response.EnsureSuccessStatusCode();
26        var stream = await response.Content.ReadAsStreamAsync();
27        return new HttpResponseStream(response, stream);
28    }
29    catch
30    {
31        response.Dispose();  // Clean up on failure
32        throw;
33    }
34}
35
36// Caller disposes the wrapper when done
37await using var result = await GetStreamAsync(client, url);
38await result.Stream.CopyToAsync(outputStream);

Buffer the content

If the payload fits in memory, copy it into a MemoryStream and dispose the response right away:

csharp
1public async Task<Stream> GetBufferedStreamAsync(HttpClient client, string url)
2{
3    using var response = await client.GetAsync(url);
4    response.EnsureSuccessStatusCode();
5
6    var memoryStream = new MemoryStream();
7    await response.Content.CopyToAsync(memoryStream);
8    memoryStream.Position = 0;  // Reset for the caller to read from the beginning
9    return memoryStream;
10    // response disposed here - safe because content is fully buffered
11}

This trades memory for simplicity. For large payloads (files, video, data exports), use the wrapper.

HttpCompletionOption and stream lifetime

HttpCompletionOption controls when GetAsync returns.

OptionBehaviorWhen to use
ResponseContentRead (default)Buffers the entire response body before returningSmall responses where you will read the whole body anyway
ResponseHeadersReadReturns as soon as headers are received, body streams lazilyLarge responses, file downloads, streaming APIs
csharp
1// Default: entire body is buffered in memory before this line completes
2using var response = await client.GetAsync(url);
3
4// ResponseHeadersRead: only headers are read, body streams on demand
5using var streamingResponse = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
6await using var stream = await streamingResponse.Content.ReadAsStreamAsync();
7// Body is read incrementally as you consume the stream

With the default, the whole body is buffered before GetAsync returns, which can cause OutOfMemoryException on large files. With ResponseHeadersRead the connection stays open while you read, so the response must stay undisposed for the entire read.

Dispose the response, not the HttpClient

HttpClient should almost never be disposed per request:

csharp
1// WRONG: creating and disposing HttpClient per request
2public async Task<string> BadPatternAsync(string url)
3{
4    using var client = new HttpClient();  // New client per request
5    using var response = await client.GetAsync(url);
6    return await response.Content.ReadAsStringAsync();
7    // client disposed here - wastes connections, causes port exhaustion
8}
9
10// CORRECT: reuse a single HttpClient instance (or use IHttpClientFactory)
11public class MyService
12{
13    private readonly HttpClient _client;
14
15    public MyService(HttpClient client) => _client = client;
16
17    public async Task<string> GetDataAsync(string url)
18    {
19        using var response = await _client.GetAsync(url);
20        return await response.Content.ReadAsStringAsync();
21        // Only the response is disposed, client is reused
22    }
23}
ResourceLifetimeDispose per request?
HttpClientApplication or service lifetimeNo (reuse or use IHttpClientFactory)
HttpResponseMessageSingle request lifetimeYes, after consuming the content
Stream from ReadAsStreamAsyncTied to the responseYes, before or alongside the response

Creating a new HttpClient per request leads to socket exhaustion under load. Keep the client long-lived and dispose only the per-request response.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms