C#中使用的关键字 - 何时以及何时不使用它? [英] C# USING keyword - when and when not to use it?

查看:152
本文介绍了C#中使用的关键字 - 何时以及何时不使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么时候我应该和不应该在使用块包装的东西。

I'd like to know when i should and shouldn't be wrapping things in a USING block.

据我所知,编译器将其转换为一个try /终于,在那里终于在对象上调用Dispose()。

From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object.

我始终在用的数据库连接和文件访问使用,但它更多的是出于习惯,而不是100%的了解。我知道你应该明确地(或有使用)的Dispose(),它控制的资源对象,以确保它们被立即释放,而不是每当CLR感觉,但多数民众赞成在我的理解打破了。

I always use a USING around database connections and file access, but its more out of habit rather than a 100% understanding. I know you should explicity (or with a using) Dispose() objects which control resources, to ensure they are released instantly rather than whenever the CLR feels like it, but thats where my understanding breaks down.

没有设置,当他们走出去的范围IDisposables?

Are IDisposables not disposed of when they go out of scope?

我只需要使用时,我的目标是利用处置将自己整理了一个使用?

Do I only need to use a USING when my object makes use of Dispose to tidy itself up?

感谢

编辑:我知道有一对夫妇using关键字其他职位,但我更感兴趣的是有关的CLR的答案,究竟怎么回事内部

I know there are a couple of other posts on the USING keyword, but I'm more interested in answers relating the the CLR and exactly whats going on internally

安德鲁

推荐答案

没有,的IDisposable 外出时范围的项目不处理。它是precisely这个原因,我们需要的IDisposable - 用于确定性清理

No, IDisposable items are not disposed when they go out of scope. It is for precisely this reason that we need IDisposable - for deterministic cleanup.

他们会的最后的被回收,如果有一个终结,将(可能)被称为 - 但可能是在未来很长一段时间(连接池等不好)。垃圾收集是依赖于内存pressure - 如果没有想更多的内存,就没有必要运行GC周期

They will eventually get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for connection pools etc). Garbage collection is dependent on memory pressure - if nothing wants extra memory, there is no need to run a GC cycle.

有趣的是(也许)有一些情况,其中使用是一种痛苦 - 当违规类引发的异常的Dispose()有时。 WCF就是一个罪犯。我已经讨论了这个话题(用一个简单的解决方法)这里

Interestingly (perhaps) there are some cases where "using" is a pain - when the offending class throws an exception on Dispose() sometimes. WCF is an offender of this. I have discussed this topic (with a simple workaround) here.

基本上 - 如果该类实现的IDisposable ,你的的一个实例(即创建它,或者别的什么),它是你的工作确保它得到处理。这可能通过用的意思,或者它可能意味着它传递到另一块code那承担相应的责任。

Basically - if the class implements IDisposable, and you own an instance (i.e. you created it or whatever), it is your job to ensure that it gets disposed. That might mean via "using", or it might mean passing it to another piece of code that assumes responsibility.

其实我已经见过调试code:

I've actually seen debug code of the type:

#if DEBUG
    ~Foo() {
        // complain loudly that smoebody forgot to dispose...
    }
#endif

(其中的Dispose 通话 GC.Sup pressFinalize

这篇关于C#中使用的关键字 - 何时以及何时不使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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