C# USING keyword - when and when not to use it?

后端 未结 3 1448

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

From what I understand, the compiler translates it into a try/finally, where the

3条回答
  •  既然无缘
    2020-12-05 07:39

    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.

    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.

    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.

    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.

    I've actually seen debug code of the type:

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

    (where the Dispose calls GC.SuppressFinalize)

提交回复
热议问题