C#:“使用";带有HttpWebRequests/HttpWebResponses的语句 [英] C#: "Using" Statements with HttpWebRequests/HttpWebResponses

查看:130
本文介绍了C#:“使用";带有HttpWebRequests/HttpWebResponses的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jon Skeet 对我的

Jon Skeet made a comment (via Twitter) on my SOApiDotNet code (a .NET library for the pre-alpha Stack Overflow API):

@ maximz2005我注意到的一件事 只需快速浏览源代码即可: 您(不会)处置WebResponses. 使用"声明FTW.

@maximz2005 One thing I've noticed just from browsing the source quickly: you don't disposed (sic) of WebResponses. "using" statements FTW.

他表示我需要将这些Web会话包装为使用".陈述.但是,我对此有一个疑问:我应该从HttpWebRequest 开始包装整个内容,还是,还是应该在"using"之外创建WebRequest?语句,然后将响应包装在里面?我感觉与众不同的是,在前者中,两个物体都将被丢弃-这是正确的吗?

He indicates that I need to wrap these Web sessions in "using" statements. However, I have a question about this: should I wrap the whole thing, starting with the HttpWebRequest, or should I create the WebRequest outside of the "using" statement and then wrap the Response inside? I have a feeling that the difference is that, in the former, both objects would be disposed of - is this correct?

谢谢.

推荐答案

HttpWebRequest本身与HttpWebResponse不同,它不是一次性的.您应该使用来包装一次性资源,以进行早期和确定的清理.正确实现的IDisposable模式允许多次调用Dispose而没有任何问题,因此,即使是外部using语句也包装了资源,以便在其自身的处理过程中将内部using语句资源进行处理仍然可以.

HttpWebRequest itself is not disposable unlike HttpWebResponse. You should wrap disposable resources with using to allow early and determined cleanup. Correctly implemented IDisposable pattern allows multiple calls to Dispose without any issues so even the outer using statement wraps resource that during its own dispose disposes inner using statement resource it is still ok.

代码示例

var request = (HttpWebRequest)WebRequest.Create("example.com"); 
using (var response = (HttpWebResponse)request.GetResponse()) 
{ 
    // Code here 
}

这篇关于C#:“使用";带有HttpWebRequests/HttpWebResponses的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆