【发布时间】:2013-03-12 17:30:00
【问题描述】:
- 如何在整个响应流回之前访问响应标头?
- 如何在流到达时读取它?
- 对于接收 http 响应的这种精细控制,HttpClient 是我的最佳选择吗?
这是一个可以说明我的问题的片段:
using (var response = await _httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead))
{
var streamTask = response.Content.ReadAsStreamAsync();
//how do I check if headers portion has completed?
//Does HttpCompletionOption.ResponseHeadersRead guarantee that?
//pseudocode
while (!(all headers have been received))
//maybe await a Delay here to let Headers get fully populated
access_headers_without_causing_entire_response_to_be_received
//how do I access the response, without causing an await until contents downloaded?
//pseudocode
while (stremTask.Resul.?) //i.e. while something is still streaming
//? what goes here? a chunk-read into a buffer? or line-by-line since it's http?
...
编辑为我澄清另一个灰色区域:我发现的任何参考都有某种阻塞语句,这将导致等待内容到达。 我阅读的引用通常访问 streamTask.Result 或 Content 上的方法或属性,我不知道哪些引用是可以的,因为 streamTask 正在进行,哪些将导致等待任务完成。
【问题讨论】:
-
我写了一个答案,但后来意识到它有点缺乏研究和懒惰。相反,我有一个后续问题,您所说的阻塞语句是什么意思?所有 HttpClient 操作都是异步的,不应该有任何东西阻止您读取单独任务的标头和内容流,从而防止它们相互阻塞。
-
@Snixtor,我的问题可能是基于一个不正确的假设,即如果我明确地等待或访问 stremTask.Result,我将读取整个内容。最终,我一直在寻找 A) 读取标题,B) 读取流的管道,我将使用伪代码编辑我的问题,以说明我想象中应该发生的事情。
-
你是对的,这是一个不正确的假设。
streamTask.Result将阻塞直到Stream可用,但它不要求整个流内容已经传输。从技术上讲,在调用streamTask.Result后可能有零个内容字节可用。 -
关于"read the stream as it come",这是默认操作。除非您特别努力不以这种方式进行操作,否则从内容流中读取将通过网络获取字节到达时。
标签: c# asynchronous c#-5.0 dotnet-httpclient