Skip to content

HCR081

Dispose streams returned from HTTP content.

Why

Streams returned by HttpClient.GetStreamAsync(...), HttpContent.ReadAsStreamAsync(...), and synchronous HttpContent.ReadAsStream() hold response/content resources until they are disposed or ownership is clearly handed to another component. Leaving those streams undisposed can keep buffers, sockets, or file handles alive longer than intended.

Bad

public async Task CopyAsync(
    HttpResponseMessage response,
    Stream destination,
    CancellationToken cancellationToken)
{
    var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
    await stream.CopyToAsync(destination, cancellationToken);
}

Better

public async Task CopyAsync(
    HttpResponseMessage response,
    Stream destination,
    CancellationToken cancellationToken)
{
    using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
    await stream.CopyToAsync(destination, cancellationToken);
}

Returning the stream is also acceptable when the caller owns it:

public async Task<Stream> OpenAsync(
    HttpClient client,
    CancellationToken cancellationToken)
{
    var stream = await client.GetStreamAsync("https://example.com", cancellationToken);
    return stream;
}

Current Detection

The implementation reports local declarations and simple assignments where a stream is materialized from HttpClient.GetStreamAsync(...), HttpContent.ReadAsStreamAsync(...), or synchronous HttpContent.ReadAsStream() and the local stream is not visibly disposed or transferred.

It recognizes using var, using (stream), await using var, await using (stream), direct Dispose() and DisposeAsync(), disposal in finally, returning the stream, and returning an object that is visibly constructed or initialized with the stream. Disposal, using ownership, direct returns, and returned-owner construction can flow through visible local alias chains populated by initializers or top-level standalone assignments. Parentheses and null-forgiving operators are transparent around stream acquisition, aliases, disposal, and direct ownership transfers. Ownership evidence for a value assigned inside a nested branch is searched from the block that declares the local, and reassignments in mutually exclusive branches, or code after a guard branch that always exits, do not invalidate earlier transfer evidence. Reassigning the local to a new owner that consumes the previous value, such as stream = new Wrapper(stream) or stream = Transform(stream), is treated as a transfer rather than a lost reference. Locals, aliases, and returned owner locals are reassignment-aware, resolved custom HttpClient lookalikes are skipped, and resolved stream methods must belong to the BCL HttpClient or HttpContent types rather than unrelated custom extensions that reuse the same names. Test code is skipped: types ending in Test/Tests, types carrying common test attributes, types deriving from a test-named base type, types in a Test, Tests, Testing, *Test, or *Tests namespace, and files under a test, tests, testassets, testapps, or acceptance directory.

The code fix converts a simple single-variable local declaration to using var. It also merges an immediately adjacent uninitialized declaration and assignment into one using declaration. Both shapes also apply to top-level statements. Existing using and await using declarations are left unchanged. Non-adjacent or nested assignments are not changed because their ownership scope requires broader control-flow judgment. Merges are withheld when a preprocessor directive guards the declaration or the assignment, so conditional compilation keeps its meaning. No fix is offered when the stream outlives the block — stored into a member or container, or passed as an argument — because disposing at block end would break the new owner. Merely calling members on the stream does not count as escaping.

Cancellation-token flow into streaming APIs is covered by HCR064; this rule focuses on stream ownership.

Known Limitations

The analyzer needs to see the stream's ownership in the same method. A stream passed to a helper call is treated as escaping because the callee might dispose it, store it, or return it. Only these count as ownership evidence: returning the stream, returning a new owner built from it, calling Dispose/DisposeAsync on it or on a previously declared alias, a using statement or declaration, and a finally block. These shapes can still report even when something later owns the stream:

  • passing the stream to a service, serializer, or helper whose disposal contract is not visible. This is a true positive when nothing owns the stream (the SimplCommerce theme import); in gRPC's ReadMessageAsync, the response that owns the stream is disposed later, which the analyzer cannot see;
  • streams stored in a returned owner assembled by a factory method, or disposal deferred through a LeaveOpen flag or a linked-disposables container (the Elastic transport pattern);
  • ownership released inside a try or catch body while the stream was declared outside it; disposal is recognized in the declaring block, in a finally, or through using;
  • custom wrappers whose disposal behavior is not visible.

When the callee's contract is to take ownership, suppress the finding with that reason or dispose the stream at the acquisition site. Test-support libraries that do not look like test code can still report.

Suppression

Suppress only when stream ownership is transferred through a pattern the analyzer cannot currently see, such as storing it in a long-lived owner that is disposed elsewhere.

References