Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable lifetime and application pool recylcing

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.

like image 991
Mike Johnson Avatar asked Dec 19 '13 00:12

Mike Johnson


1 Answers

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.

like image 116
Jon Egerton Avatar answered Nov 06 '22 05:11

Jon Egerton