Does the “using” keyword mean the object is disposed and GC’ed?

You’re talking about two very different things.

The object will be disposed as soon as the using-block ends. That doesn’t say anything about when it is garbage collected. The only time heap memory is released is when a garbage collection occurs – which only happens under memory pressure (unless you use GC.Collect explicitly).

Disposing an object simply means calling its Dispose method. That most often means releasing either a scarce resource, or a native resource (in practice, all scarce resources are native – sockets, files, …). Now, it’s handy that the lifetime of the disposable object in your case is limited in scope, so it could theoretically be collected as soon as the using-block ends – however, that doesn’t really happen in practice, since the .NET runtime tries to avoid collections – they’re expensive. So until you cross a memory allocation threshold, no collection is going to happen, even though you have a dead object on the heap.

So what’s the point of Dispose? Nothing to do with managed memory. You don’t really care about managed memory, and you shouldn’t expect that Dispose will actually be called – it doesn’t have to be. The only thing that has to be called by the runtime is the finalizer, and you can only ever use that for disposing of native resources – in fact, there’s no guarantee if the objects you have a reference to still exist by the time the finalizer runs – the managed memory might have already been reclaimed by then. That’s why you never handle managed resources in a finalizer.

So yes, she was completely right. The point is that IDisposable has nothing to do with the garbage collector. Disposed does not mean garbage collected.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)