Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async read methods in System.Net.Http.HttpContent missing CancellationToken overload

public async Task<Request> GetRequestAsync()
{
  var response = await _httpClient.GetAsync(_requestUri, _cancellationToken);
  return await response.Content.ReadAsAsync<Request>();
}

I've got this code that passes an instance of CancellationToken into the _httpClient.GetAsync call. I would expect I also could pass a CancellationToken into the response.Content.ReadAsync call, but there doesn't seem to be any overload accepting a CancellationToken.

I would expect the response.Content.ReadAsAsync call could also take some time. Shouldn't it then be cancellable?

Is this by design, or am I missing something here?

like image 216
Andreas Presthammer Avatar asked Jul 14 '26 09:07

Andreas Presthammer


1 Answers

It's not part of the API, however, you could register a Dispose against the token:

CancellationToken ct; //passed in
ct.Register(() => myHttpContent.Dispose()); 
string content;
try
{
    content = await myHttpContent.ReadAsStringAsync();
}
catch(Exception) //suspect an ObjectDisposedException, but worth checking
{
    if(ct.IsCancellationRequested)
    {
        //cancellation was requested
        //underlying stream is already closed by the Dispose call above
    }
}
like image 160
spender Avatar answered Jul 17 '26 21:07

spender