0

我想等待所有响应一次。

for (int i = 0; i < N; i++)
{
    request = (HttpWebRequest)WebRequest.Create(url[i]);
    // init other request headers...

    // get response
    using (HttpWebResponse response = await Web.GetHttpWebResponseAsync(request))
    {
        string strResponse = Web.ConvertHttpWebResponseToString(response, System.Text.Encoding.GetEncoding("utf-8"));
    }
}

它可以工作,但是在加载 i = 0 的数据(长时间)时循环等待的第二步。我希望所有 N 个请求一次等待。我试试这个:

List<Task<HttpWebResponse>> ts = new List<Task<HttpWebResponse>>();
for (int i = 0; i < N; i++)
{
    request = (HttpWebRequest)WebRequest.Create(url[i]);
    // init other request headers...

    // save task in list
    ts.Add(Web.GetHttpWebResponseAsync(request));
}

Task.WaitAll(ts.ToArray());

for (int i = 0; i < N; i++)
{
    string strResponse = Web.ConvertHttpWebResponseToString(ts[i].Result, System.Text.Encoding.GetEncoding("utf-8")); // <== but I get error access to disposed stream.
}

我如何一次等待所有回复?
谢谢你的帮助。

public static string ConvertHttpWebResponseToString(HttpWebResponse response, Encoding encoding)
{
    string data = "";
    System.IO.Stream responseStream = response.GetResponseStream(); // <-- error on this
    using (System.IO.StreamReader reader = new StreamReader(responseStream, encoding))
    {
        data += reader.ReadToEnd();
    }
    responseStream.Close();
    return data;
}

编辑
我在自己的函数中替换响应并且它有效:

public static async Task<string> GetRespStr(HttpWebRequest request)
{
    string strResponse = null;
    using (HttpWebResponse response = await Web.GetHttpWebResponseAsync(request))
    {
        strResponse = Web.ConvertHttpWebResponseToString(response, System.Text.Encoding.GetEncoding("utf-8"));
    }
    return strResponse;
}

void main()
{
    for (int k = 0; k < cnt; k++)
    {
        request = (HttpWebRequest)WebRequest.Create(href[k]);
        tasks.Add(GetRespStr(request));
    }

    Task.WaitAll(tasks.ToArray());

    for (int k = 0; k < cnt; k++)
    {
        result.Add(tasks[k].Result);
    }
}

问题为我解决了,谢谢。

4

0 回答 0