问题
Is there any way to set the life cycle of a static variable - ie: how long it's kept alive before being reset? I was hoping there may be an attribute which can be applied.
回答1:
Static members are associated with the type itself, not with an instance of the type. Therefore their lifecycle is limited to the timing and ordering of their creation, and they don't get "reset" by instances of the type.
回答2:
The lifetime of a value in a Static variables is the same as it's containing AppDomain. Ie. if you get a new AppDomain (because your IIS application restarts), you get a new copy of the static variable.
回答3:
In my case, as I'm using ASP.NET, the item in question should remain 'live' for the lifecycle of one request, so after thinking about it the HttpContext["Items"] collection would be best. Eg, instead if:
private static SomeObject _books;
protected static SomeObject Books
{
get
{
if (_books == null) {
_books = new SomeObject();
}
return _books ;
}
}
protected static SomeObject AVariable
{
get
{
SomeObject books = HttpContext.Current.Items["books"] as SomeObject;
if (books == null) {
books = new SomeObject();
HttpContext.Current.Items["books"] = books;
}
return books;
}
}
回答4:
A static variable is held for the lifespan of the application and shared between all threads. It is only reset when the application restarts (a web.config change for example).
If this is for something like caching I'd suggest setting a timer to update the value at regular intervals.
来源:https://stackoverflow.com/questions/11394203/lifecycle-of-static-variables