正确的方法来停止ReadAsStreamAsync

时间:2013-11-15 10:59:52

标签: c# asynchronous httprequest async-await dotnet-httpclient

我的代码如下:

_req = new HttpRequestMessage(HttpMethod.Get, _uri);
_response = await _httpClient.SendAsync(_req, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

var rawResponse = new byte[_maxContentLength];

using (var responseStream = await _response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
    int read;
    int offset = 0;

    do
    {
        read = await responseStream.ReadAsync(rawResponse, 0, rawResponse.Length).ConfigureAwait(false);
        html += Encoding.UTF8.GetString(rawResponse, 0, read);
        offset += read;

        if (offset > _maxContentLength)
        {
            return Error("Too big");
        }

    } while (read != 0);
}

并且“返回Error()”足以释放流和套接字来获取下一个url?

//编辑: 对于某些页面await responseStream.ReadAsync挂起并且永不返回

1 个答案:

答案 0 :(得分:0)

尝试创建CancellationTokenSource并在您想要停止时调用Cancel。我假设您无法在开头读取Content-Length标头,因为响应是块编码的?