HttpResponse 是否以“使用”方式工作?没有明确的 response.close() 的情况下阻塞

发布于 2024-08-08 19:37:32 字数 559 浏览 3 评论 0原文

我试图对此进行澄清:

方法 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔戏命师 2024-08-15 19:37:32

Using 只是转换为 Try/Finally 块,该块在 Finally< 中调用 .Dispose() /代码> 块。您可以使用 Reflector 来查找生成的代码。您还可以使用它来查看方法的作用。在这种情况下,HttpWebResponse 上的 Dispose() 方法Close() 执行相同的操作,这意味着它实际上在这里有语义差异。

Using 通常具有在对象超出范围时立即释放对象使用的资源的好处。这对于 GDI+ 或文件句柄之类的东西很有用,但对于 HttpWebResponse 来说可能有点不同。由于对特定对象了解不够,我猜测 Close() 并不会真正释放任何资源,因此不需要 Dispose() 调用 < code>Close() 也是如此。也许这种行为是有正当理由的。

Using simply translates into a Try/Finally block which calls .Dispose() in the Finally 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, the Dispose() method on HttpWebResponse does not do the same as Close() 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 of HttpWebResponse it might be a little bit different. Not knowing enough about that particular object my guess would be that Close()ing it doesn't really release any resources, so there is no need for Dispose() calls Close() too. And maybe there are valid reasons for that behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文