Garbage collection of static members

前端 未结 4 2054
逝去的感伤
逝去的感伤 2020-12-10 05:52

Will static members be ever collected by the garbage collector?

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 06:14

    The short answer... No; all current implementations of the .NET garbage collector will not collect objects strongly referenced by static class member fields, until the Application Domain those static class member field strong references are associated with, is torn down.

    The longer answer... Potentially yes; the garbage collector bases its decision to collect an object on reachability of the object, not on references (strong or weak) to the object. In theory, if the garbage collector could determine that no code would ever require a certain object again from a certain point onwards (that is, the object is not reachable from any code path), the GC would be allowed to collect that object, even if it were still strongly referenced by static class member fields. This is perfectly allowable, since you'd never notice, since no code would ever try access the static class member field that holds the reference to the object. You might ask, so why do I care if I am never going to access the object again via any of the strong references I hold to it? The reason you'd care is side-effects. For instance, you might assume by assigning a static class member field a reference to a SafeHandle object, representing a unmanaged resource, that the SafeHandle object would never be closed and would thus keep the unmanaged "object" it represents alive. This is only true for the current implementations of the GC. A future implementation of the GC could collect objects strongly referenced by static class member fields if those objects were no longer reachable by any of the remaining program code.

提交回复
热议问题