Do static members ever get garbage collected?

好久不见. 提交于 2019-12-17 02:31:45

问题


Do static member variables ever get garbage collected?

For example, let's use the following class.

public class HasStatic {
    private static List<string> shared = new List<string>();

}

And supposed that it's used like this:

//Startup
{
HasStatic a = new HasStatic();
HasStatic b = new HasStatic();
HasStatic c = new HasStatic();
HasStatic d = new HasStatic();
//Something
}
//Other code
//Things deep GC somewhere in here
HasStatic e = new HasStatic();

When a, b, c, and d are garbage collected does the static member shared get collected as well? Could e possibly get a new instance of shared?


回答1:


No, static members are associated with the Type, which is associated with the AppDomain it's loaded in.

Note that there doesn't have to be any instances of HasStatic for the class to be initialized and the shared variable to have a reference to a List<string>.

Unless you're considering situations where AppDomains get unloaded, static variables can be regarded as GC roots forever. (Of course, if something changes the value of HasStatic.shared to reference a different instance, the first instance may become eligible for garbage collection.)




回答2:


The only thing I would add to Jon's excellent answer is that CLR 4 supports "collectible assemblies". If you dynamically generate a collectible assembly then the statics of its types go away when the assembly is garbage collected.

See this msdn article for a brief overview of the feature:

http://msdn.microsoft.com/en-us/library/dd554932%28VS.100%29.aspx



来源:https://stackoverflow.com/questions/6600093/do-static-members-ever-get-garbage-collected

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