等待几个web响应同时

时间:2015-01-12 02:40:13

标签: c# asynchronous task webrequest webresponse

我想等一次所有回复。

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);
    }
}

问题解决了我,thx。

0 个答案:

没有答案