c# webrequest 挂起

标签 c# .net

我在做一个项目,多次调用一个网址

request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse();    

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

错误:WAITING 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()

内部异常:

最佳答案

尝试以下操作:

var response = request.GetResponse();
//do stuff with response
response.Close();

WebResponse 实例保持事件连接,您必须在与同一服务器建立新连接之前关闭该连接。

您也可以使用 using 子句来做到这一点,这完全取决于您:

using (var response = request.GetResponse())
{
    //do stuff with response
}

关于c# webrequest 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13156608/

相关文章:

c# - ToggleButton 样式仅适用于最后一个 ToggleButton

c# - BindingExpression 路径错误 : property not found on 'object'

c# - ReSharper 代码注释异步任务<T>

c# - 排序、过滤和分页 MVC

.net - 在Powershell中运行外部程序的替代方法

c# - 将值传递给方法

c# - GZipStream 提示 header 中的魔数(Magic Number)不正确

c# - GetService 与 IOptionsMonitor<Settings> 返回 null 对象

.net - gcroot 集合 - 元素访问

c# - xamarin:无法解析程序集:System.Security