HttpResponse 是否以“使用”方式工作?没有明确的 response.close() 的情况下阻塞
我试图对此进行澄清:
方法 1:
Dim request = CreateRequest(uri) //some uri
Dim response = DirectCast(request.GetResponse, HttpWebResponse)
response.Close()
方法 2:
Dim request = Createrequest(uri)
Using response = DirectCast(request.GetResponse, HttpWebResponse)
End Using
当我在本地计算机上使用方法 1 和方法 2 来连接并从远程计算机 X 获取响应时,它们都工作正常。
当我在远程计算机 Y 上使用此代码从 X 获取响应时,只有方法 1 有效,而对于方法 2,我得到了
System.Net.WebException: The operation has timed out
上述方法之间有什么区别以及可能存在的问题是什么?
I was trying to get clarification on this:
Method-1:
Dim request = CreateRequest(uri) //some uri
Dim response = DirectCast(request.GetResponse, HttpWebResponse)
response.Close()
Method-2:
Dim request = Createrequest(uri)
Using response = DirectCast(request.GetResponse, HttpWebResponse)
End Using
When I used both Method-1 and Method-2 on my local machine to connect and get a response from a remote machine X, both of them worked properly.
When I used this code on a remote machine Y to get response from X, only the Method-1 is working, and for Method-2, I am getting
System.Net.WebException: The operation has timed out
What's the difference between the Methods mentioned above and what might be the possible problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Using
只是转换为Try
/Finally
块,该块在Finally< 中调用
.Dispose()
/代码> 块。您可以使用 Reflector 来查找生成的代码。您还可以使用它来查看方法的作用。在这种情况下,HttpWebResponse
上的Dispose()
方法不与Close()
执行相同的操作,这意味着它实际上在这里有语义差异。Using
通常具有在对象超出范围时立即释放对象使用的资源的好处。这对于 GDI+ 或文件句柄之类的东西很有用,但对于 HttpWebResponse 来说可能有点不同。由于对特定对象了解不够,我猜测Close()
并不会真正释放任何资源,因此不需要Dispose()
调用 < code>Close() 也是如此。也许这种行为是有正当理由的。Using
simply translates into aTry
/Finally
block which calls.Dispose()
in theFinally
block. You can use Reflector to find what code is generated. You can also use it to take a look at what a method does. In this case, theDispose()
method onHttpWebResponse
does not do the same asClose()
which means it has in fact semantic differences here.Using
usually has the benefit of releasing resources used by an object immediately when it goes out of scope. This is useful for things like GDI+ or file handles, but in the case ofHttpWebResponse
it might be a little bit different. Not knowing enough about that particular object my guess would be thatClose()
ing it doesn't really release any resources, so there is no need forDispose()
callsClose()
too. And maybe there are valid reasons for that behavior.