Skip to content

[API Proposal]: Expose overloads of HttpContent.LoadIntoBufferAsync taking a CancellationToken #102659

Closed
@andrewhickman-aveva

Description

@andrewhickman-aveva

Background and motivation

HttpContent.LoadIntoBufferAsync and HttpContent.LoadIntoBufferAsync(long) currently forward to overloads which take a cancellation token, passing CancellationToken.None.

public Task LoadIntoBufferAsync(long maxBufferSize) =>
LoadIntoBufferAsync(maxBufferSize, CancellationToken.None);

HttpClient also uses this API but passes a cancellation token:

response.Content.LoadIntoBuffer(_maxResponseContentBufferSize, cts.Token);

It would be useful for external consumers to be able to pass a cancellation token, similar to HttpContent.CopyToAsync(Stream, CancellationToken

API Proposal

 namespace System.Net.Http;
 
 public class HttpContent
 {
     public Task LoadIntoBufferAsync();
     public Task LoadIntoBufferAsync(long maxBufferSize);
+    public Task LoadIntoBufferAsync(CancellationToken cancellationToken);
+    public Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancellationToken);
 }

API Usage

using var client = new HttpClient();
using var response = await client.GetAsync("https://example.com", HttpCompletionOption.ResponseHeadersRead);

using (var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30))
{
    var maxBufferSize = 134217728L;
    await response.LoadIntoBufferAsync(maxBufferSize, timeoutCts.Token);
}

Alternative Designs

If the HttpContent has been created by HttpClient, it could internally track cancellation based on the token passed to SendAsync. However I don't think this is consistent with existing HttpContent methods like CopyToAsync.

Risks

None

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Net.Httphelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions