C# WebRequest卡住了

3
我正在从事一个项目,它会多次调用一个网络地址。
request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse();    

这是我的代码。它在一个循环中,前两次工作正常,但到第三次迭代时卡住了。没有崩溃或错误。请帮忙解决问题。任何帮助都将不胜感激。

错误:等待20分钟后。

System.Net.WebException was unhandled
Message=The operation has timed out
Source=System
StackTrace:
   at System.Net.HttpWebRequest.GetResponse()
   at ConsoleApplication1.Program.Main(String[] args) in C:\WorkSpace\ConsoleApplication1\ConsoleApplication1\Program.cs:line 48
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

内部异常:


2
你关闭了连接吗? - leppie
1个回答

5
请尝试以下方法:
var response = request.GetResponse();
//do stuff with response
response.Close();
WebResponse 实例保存了当前的连接,如果您要建立到同一服务器的新连接,则必须关闭该连接。
您也可以使用 using 语句来实现这一点,具体取决于您的选择:
using (var response = request.GetResponse())
{
    //do stuff with response
}

谢谢,你救了我——我的C#程序最终会锁定,因为我没有按照你上面的建议关闭响应! - Neal Davis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接