Finalize method guidelines and best practices in C# [closed]
-
08-06-2021 - |
質問
I have recently encountered an issue that is related to code running in the Finalize method overload.
I am mostly aware of issues that are related to memory management/performance, but i am interested whether there are any guidelines for "which code should/shouldn't go in a Finalize method" ?
For example:
- Do not throw exceptions from within a Finalize method.
- Code should execute quickly.
- Do not raise events (?)
- Etc...
The behaviour in my case was seen due to an event being raised that caused some exception.
So my question is -- what guidelines must i follow (perhaps even enforce using some tools) regarding finalize methods?
解決
Finalizing is ONLY for getting rid of unmanaged resources
From MSDN
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.
Finalize operations have the following limitations:
The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method.
The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
The thread on which the finalizer is run is unspecified
他のヒント
There should be no reason you're calling finalize. Even though it's open to you for overriding, the best practice in using finalize is not to use them. Instead, inherit from IDisoposable. Not only is this a best practice, it doesn't interfere with garbage collection, and has the convenient ''using'' clause to auto dispose. Inheriting this class also notes to other developers that this is an object that has resources to dispose of, and I'm a particular manner. I even think the GC will call dispose during its garbage run.
In short, anything you can do with finalize is better done with dispose.