问题
When I read a few articles about memory management in C#, I was confused by Finalizer methods.
There are so many complicated rules which related with them. For instance, nobody knows when the finalizers will be called, they called even if code in ctor throws, CLR doesn't guarantee that all finalizers be called when programs shutdowt, etc.
For what finalizers can be used in real life?
The only one example which I found was program which beeps when GC starts.
Do you use Finalizers in your code and may have some good samples ?
UPD:
Finalizers can be used when developpers want to make sure that some class always disposed correctly through IDisposable. (link ; Thanks Steve Townsend)
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4088491/good-samples-of-using-finalizers-in-c-sharp