I understand the lifetime of static variables in relation to applications (console/windows) but I'm not sure if I am understanding their lifetime when in the context of web apps (asp.net, mvc, web api, etc).
From what I understand, when IIS recycles the app pool, static variables are reset to their type's defaults (integrals = 0, reference types = null, etc), but I'm wondering if inline initializers are re-initialized after recycles or will the type defaults ALWAYS be assigned regardless?
Example(s):
// example 1
static class StaticRandom
{
private static Random rng = new Random();
}
In the above, would the static field rng be reinitialized to new Random() when called for the first time after a recycle? Or do I need to implement null checks before attempting to use the variable, such as:
// example 2
static class StaticRandom
{
private static Random rng = null;
public static Next()
{
if (rng == null)
rng = new Random();
return rng.Next();
}
}
Am I correct in assuming that after an IIS recycle, the rng variable in example 1 would be null until reinitialized like in example 2?
NOTE: I'm fully aware of the thread safety issues in the above example, it's just a quick example to illustrate my question. In a real-world scenario of the above idea, I would implement a proper locking pattern.
Ok, so couldn't help myself, and did a quick test.
This was pretty much as per your example 1, except with a page output so I could do it without being attached to the process,
It confirmed what I thought - The static will be reset to the inline initialize value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With