3
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 调用也需要一些时间。那它不应该是可以取消的吗?

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

4

1 回答 1

2

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

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
    }
}
于 2013-07-05T16:36:16.550 回答