开发者

Do I have to use a “using” statement in a short method?

开发者 https://www.devze.com 2023-04-12 14:01 出处:网络
Do I have to use a using开发者_JAVA技巧 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?

Do I have to use a using开发者_JAVA技巧 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.


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:

  • files get left open and cause access-exceptions (FileStream)
  • connections get left open and cause pool saturation (DbConnection)
  • unmanaged handles get saturated and cause resource starvation (any winforms/etc)
  • transactions get left open and cause blocking (TransactionScope / DbTransaction)
  • etc

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号