在前一个呼叫仍在进行时,无法重新调用BeginGetRequestStream / BeginGetResponse

时间:2015-05-19 07:35:15

标签: c# multithreading httpwebrequest

我在Task工厂内部调用httpwebresponse,并在执行1次后抛出异常
Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress
我的代码如下:

for (int i = 0; i < tsk.Length; i++) 
{ 
   tsk[i] = Task.Factory.StartNew((object obj) => 
   { 
        System.Diagnostics.Stopwatch watch = Stopwatch.StartNew();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        watch.Stop(); 
   }, i);
}

如何解决此问题

1 个答案:

答案 0 :(得分:3)

您一次又一次使用相同的HttpRequest对象:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

每次尝试同时重用HTTP连接并获得异常时,必须重新创建它:

HttpWebRequest request = WebRequest.Create("url");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();