Good samples of using Finalizers in C#

倖福魔咒の 提交于 2019-11-30 09:19:25
Steve Townsend

There is an exhaustive discussion of Finalizer usage, with examples, here. Link courtesy of @SLaks at a related answer.

See also here for a more concise summary of when you need one (which is "not very often").

There's a nice prior answer here with another good real-world example.

To summarize with a pertinent extract:

Finalizers are needed to guarantee the release of scarce resources back into the operating system like file handles, sockets, kernel objects, etc.

For more correct real-world examples, browse around affected classes in the .Net Framework this MSDN search:

http://social.msdn.microsoft.com/Search/en-US?query=%22.Finalize%22&ac=8

One valid reason I can think of when you might need to use a finalizer is if you wrap a third-party native code API in a managed wrapper, and the underlying native code API library requires the timely release of used operating system resources.

luckyluke

The best practice known to me is plain simple don't use them. There might however be some corner cases when you want to use a finalizer, particularly when dealing with unmanaged objects and you can't implement Dispose pattern (I do not know legacy issues) then you can implement Finalize method with caution (and it could reduce the performance of your system, make your objects undead and other possibly weird scenarios, minding the exceptions as they are uncatchable:)).

In 99% of cases just write the use Dispose pattern and use this method to clean after yourself and everything will be fine.

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