Reputation: 27683
Do I have to use a using
statement to dispose immediately even in a method? Or will the ending of the method cause an automatic Dispose
of all local variables including graphics?
(I’m asking this because I’ve seen examples that have Dispose
calls at the end of methods, and wanted to know if that’s really necessary.)
Thanks.
Upvotes: 1
Views: 248
Reputation: 52655
You don't ever have to dispose of an object. But if you want to release unmanaged resources earlier rather than whenever the GC gets around to it (which is when it processes the fReachable queue) then yes you should since the scope of of a method does not determine when a disposable object's finalize will be called.
For more you might want to read Jeffrey Richter's Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
As delnan noted if there's a hard limit to the resources you're using you're much more likely to impacted if you let it get reclaimed by the GC rather than calling Dispose. DB connections are a good example of this kind of reasource and is certainly the reason why the NumberOfReclaimedConnections performance counter got created.
Upvotes: 4
Reputation: 5980
Yes, use using
. It is a great statement.
Actually if you don't call Dispose
(either manually or by using using
), you can end up in a situation where your managed memory is stil quite empty, but unmanaged resources are depleted. Eventually it can cause a deadlock because other objects or other processes will wait for your unmanaged resources and you will wait for them. (Garbage collector won't run, because managed memory still won't be full.)
So please call Dispose
as soon as you can. Once you don't need an object which has got that method defined, call it.
Upvotes: 0
Reputation: 1063013
Yes, you do. Going out of scope does not do anything; it does not call Dispose()
, it does not garbage-collect, it does not call a finalizer.
If the type is IDisposable
, then yes. It is your job to tidy up after yourself (assuming that the object is actually "done with" at this point).
Possible side-effects of not doing this:
FileStream
)DbConnection
)TransactionScope
/ DbTransaction
)basically, bad things.
Furthermore, in most cases where you see Dispose()
at the bottom of the method, a using
would be preferable. There are some cases where that isn't possible (fields on an object, for example), but the point remains: it sounds like those are bad examples.
Upvotes: 10