I have an ASP.Net 4.0 website on a shared hosting system. Applications are recycled after 20 minutes of inactivity.
In my application some static variables are initialized in application_start.
When the next request comes in, the application should be restarted, application_start executed and the static variables reset.
After the period of inactivity, when I access pages that depend on the static vars, they are null and that creates errors.
Since these variables are initialized in application_start, it seems odd that after the period of inactivity that they would be null since the application restarting would reinitialize them.
In fact, when I see the null reference errors, recycling the app pool (and executing application_start) solves the problem until the next time the application is dropped from memory.
I’m wondering if some other type of system memory problem is occurring when the application is removed from memory, because if the application was simply being recycled, the reinitialization of the static variable in application_start would mean there would be no reason for the statics to be null.
Since static variables are not garbage collected they should never be null after initialization.
The errors never occur on any developer machines, only on the shared hosting system. What could be some other causes for static variables initialized in application_start to become null?
There is no code that resets the variables. They are private fields that only contain access via a get method.
Code:
private static List<State> stateList;
public static void LoadStaticCache()
{
var service = DependencyResolver.Current.GetService<ILocationService>();
stateList = service.GetAllStates().ToList();
}
public static List<State> GetStates()
{
return stateList;
}
When the inactivity period is met, the next time the stateList is accessed, it is null.
However, it is always initialized in application_start. How can it ever be null unless it is a system problem?
protected void Application_Start()
{
StaticCache.LoadStaticCache();
}
Recycling the Application Pool fixes the issue 100% of the time.
It sounds like your issue is related to session timeout.
Unlike earlier versions of IIS, if your hosted server is running IIS 7.0 or higher with Integrated Mode, Application_Start will not have access to the current HTTP context since it doesn’t exist yet. IIS 7.0 in Classic Mode will have no issues.
In either case, a solution would be to move your initializations to Session_Start in Global.asax: