C# Why dispose when we already have finalizers [duplicate]

半腔热情 提交于 2020-07-09 02:59:21

问题


I've been hearing advices about putting codes to handle unmanaged resources in both finalizer and Dispose() method. What I don't understand is that since finalizers are called when GC occurs so we could technically assume that it gets called all the time. In that case why bother disposing an object? Am I missing something?


回答1:


In that case why bother disposing an object?

Because you don't have control over when a finalizer runs. It could well be that the GC runs too in-frequent and a program that relies on finalizers alone could crash for lack of resources (filehandles, db-connections).

The best-practice (Disposable pattern) uses finalizers as the backup-plan, quite often the execution of a finalizer is considered a bug that needs fixing.




回答2:


Quoting from MSDN http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx

Although finalizers are effective in some cleanup scenarios, they have two significant drawbacks:

  • The finalizer is called when the GC detects that an object is eligible for collection. This happens at some undetermined period of time after the resource is not needed anymore. The delay between when the developer could or would like to release the resource and the time when the resource is actually released by the finalizer might be unacceptable in programs that acquire many scarce resources (resources that can be easily exhausted) or in cases in which resources are costly to keep in use (e.g., large unmanaged memory buffers).

  • When the CLR needs to call a finalizer, it must postpone collection of the object’s memory until the next round of garbage collection (the finalizers run between collections). This means that the object’s memory (and all objects it refers to) will not be released for a longer period of time.



来源:https://stackoverflow.com/questions/19902936/c-sharp-why-dispose-when-we-already-have-finalizers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!