Static members collect garbage collection?

Static member variables ever garbage collect?

For example, you can use the following class.

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

And suggested that he 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, is the static shared member going? Can e get a new instance of shared ?

+29
garbage-collection c # static-members
Jul 06 '11 at 16:50
source share
2 answers

No, static members are associated with a type that is associated with the AppDomain loaded by it.

Note that there must be no HasStatic instances for the initialized class, and the shared variable must have a reference to List<string> .

If you do not consider situations when AppDomains are unloaded, static variables can be considered as roots of GC forever. (Of course, if something changes the value of HasStatic.shared to refer to another instance, the first instance may be entitled to garbage collection.)

+56
Jul 06 2018-11-11T00:
source share

The only thing I would like to add to John is that the CLR 4 supports โ€œcollectible buildsโ€. If you dynamically generate a assembly, then the statics of its types disappear when the assembly collects garbage.

See this msdn article for an overview of the function:

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

+25
Jul 06 2018-11-17T00:
source share



All Articles