c #webrequest挂起

gre*_*ics 3 .net c#

我正在研究一个多次调用网址的项目

request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse();    
Run Code Online (Sandbox Code Playgroud)

这是我的代码.它处于一个循环中,它可以工作2次,但在第三次迭代时它会挂起.没有崩溃或错误.请帮忙.任何帮助将不胜感激.

错误:等待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()
Run Code Online (Sandbox Code Playgroud)

的InnerException:

And*_*rpi 5

请尝试以下方法:

var response = request.GetResponse();
//do stuff with response
response.Close();
Run Code Online (Sandbox Code Playgroud)

该WebResponse实例保持活动连接,您必须在为同一服务器建立新连接之前关闭该连接.

你也可以用一个using条款来做这件事,这取决于你:

using (var response = request.GetResponse())
{
    //do stuff with response
}
Run Code Online (Sandbox Code Playgroud)