问题
I need to implement several application-level behavior in a project I'm currently working on. There are several things I need to get my head around: 1. Where and how do I define application level variables? 2. What is the lifetime of these variables? or more accuratly, in what scenarios are they discarded? (Application pool recycle? App binaries dropped from memory and recompiled on the next request? etc.) 3. Is the global.asax file a good place to put a session counter, or maybe storing the value to a DB / file is a better way of persisting this kind of data?
Any comments or ideas are welcome. Thank you! -Elad
回答1:
Application-level variables have an application life-time. It means that it the application pool is recycled, they're discarded.
The application pool can be recycled for different reasons. IIS 6/7 can be configures so that the app pool is recycled after a certain amount of time, after a certain number of request or at specified intervals.
You set an application variable this way:
Application["DbConfig"] = "my value";
but you have to be aware of the problems you might encounter if you try to set/access in different place. You have to adopt a way to lock the variables when they're updated.
I us the web.config
for all the configuration parameters and then I've created my own class which I use to store application fields:
namespace Web.My
{
public class Application
{
public static string ApplicationStorageFolder
{
get
{
return (System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~"), "_AppStorage"));
}
}
}
}
If I need set some fields I do it at the application startup Application_Start
If you need to persist infos you can create your own config file (xml or simple text) to store and read values at the application startup and shutdown. You can serialize your class in a XML file so you can ready it, repopulating your properties easily.
A db would be fine as well.
I would do the same with the session counter.
来源:https://stackoverflow.com/questions/5548601/global-asax-scope-and-lifetime-clarification