Static lifetime and reuse of application pool

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):

// example 1 static class StaticRandom { private static Random rng = new Random(); } 

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.

+8
c # iis static-variables
source share
1 answer

Good, so I could not help myself, and did a quick test.

This was basically in line with your example 1, with the exception of the page output, so that I can do this without being bound to a process,

This confirmed what I thought. The static value will be reset for the inline initialize value.

+5
source share

All Articles