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调用也可能需要一些时间。它不应该被取消吗?
这是设计,还是我在这里遗漏了什么?
答案 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
}
}