I understand the lifetime of static variables in relation to applications (console / windows), but I'm not sure if I understand their lifespan in the context of web applications (asp.net, mvc, web api, etc.) ..
From what I understand when IIS recycles an application pool, the reset static variables refer to their default types (integrals = 0, reference types = null, etc.), but I'm wondering if initialization initializers are reinitialized after repeated loops or will the default values be ALWAYS assigned?
Example (s):
In the above case, would the rng static field be re-initialized for the new Random () when called for the first time after reuse? Or I need to implement error checking before trying to use this variable, for example:
// example 2 static class StaticRandom { private static Random rng = null; public static Next() { if (rng == null) rng = new Random(); return rng.Next(); } }
Do I correctly assume that after disposing of IIS, the rng variable in example 1 will be null until reinitialized, as in example 2?
NOTE. . I am fully aware of thread safety issues in the above example, this is just a quick example to illustrate my question. In the real scenario of the above idea, I would follow the correct lock pattern.
Mike johnson
source share