Static fields are never garbage collected. Take a look at Jeffrey Richter's article .
Static fields are treated as root using the Garbage Collector, so the Garbage Collector will always assume that static fields are used.
Static fields are initialized when the owner type is loaded. The JIT compiler loads a type when it needs to build a method and sees a link to that type. After loading, the type remains there for all AppDomain life cycles, so all links related to the type (static fields) will be considered as used links and will not be garbage collected.
In addition, with respect to this statement:
I can’t find out how long these static variables live, they get (the static constructor starts) when they touch the first time.
Technically, a static variable is not necessarily “affected” for the first time in a static constructor. Consider the class as follows:
public static class Test { private static MyType myType; static Test() { myType = new MyType(); } }
A static constructor (type constructor) will never be called unless you have code that executes and references this type, for example var x = Test.myType; . Well, that probably depends on what exactly “touched” that is.
Answer:
Static types live in AppDomain since they first loaded until the AppDomain is unloaded. Thus, you do not need to extend the life of the device while the AppDomain is running.
source share