Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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
    }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.