Why does the Finalize/Destructor example not work in .NET Core?

后端 未结 2 2012
南笙
南笙 2020-12-30 02:43

I\'m trying to learn how finalization and destructor works in C#, I tried to run the code in the System.Object.Finalize example(code copy-pasted, no changes made), but the o

相关标签:
2条回答
  • 2020-12-30 03:09

    Finalization won't occur until the garbage collector runs. Garbage collection doesn't run unless it needs to (e.g. you're low on memory), or if you force it to run.

    Try adding

    System.GC.Collect();
    

    to your code and see if the finalizer runs in that situation.

    0 讨论(0)
  • 2020-12-30 03:30

    Putting together information from comments by Peter Duniho and Henk Holterman and expanding on it further:

    This behavior is in violation of the C# 5.0 spec from Microsoft and the current draft of the C# 6.0 spec from Microsoft, which say:

    Prior to an application's termination, destructors for all of its objects that have not yet been garbage collected are called, unless such cleanup has been suppressed (by a call to the library method GC.SuppressFinalize, for example).

    But it's not a bug, .Net Core intentionally diverged from the .Net Framework behavior, as explained in a corefx issue:

    Currently, a best-effort attempt is made to run finalizers for all finalizable objects during shutdown, including reachable objects. Running finalizers for reachable objects is not reliable, as the objects are in an undefined state.

    Proposal

    Don't run finalizers on shutdown (for reachable or unreachable objects)

    Under this proposal, it is not guaranteed that all finalizable objects will be finalized before shutdown.

    Presumably due to this, the C# 5.0 spec from ECMA weakened this requirement, so .Net Core does not violate this version of the spec:

    Prior to an application’s termination, an implementation should make every reasonable effort to call finalizers (§15.13) for all of its objects that have not yet been garbage collected, unless such cleanup has been suppressed (by a call to the library method GC.SuppressFinalize, for example). The implementation should document any conditions under which this behavior cannot be guaranteed.

    0 讨论(0)
提交回复
热议问题