System.Net.Http.HttpContent中的异步读取方法缺少CancellationToken重载

时间:2013-07-05 16:05:01

标签: c# .net http httpclient

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

我有这个代码将CancellationToken实例传递给_httpClient.GetAsync调用。我希望我也可以将CancellationToken传递给response.Content.ReadAsync调用,但似乎没有任何重载接受CancellationToken。

我希望response.Content.ReadAsAsync调用也可能需要一些时间。它不应该被取消吗?

这是设计,还是我在这里遗漏了什么?

1 个答案:

答案 0 :(得分:1)

它不是API的一部分,但是,您可以针对令牌注册Dispose

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
    }
}