views:

34

answers:

1

1) In a standard .Net application, are classes loaded as they are required? (e.g. If I have a class with a static constructor, is that static constructor only run the first time that class is needed?)

2) In an ASP.Net MVC (or web forms) application, is the static constructor invoked on every request that uses it? Or is it only for the first request that uses it?

3) In general, what is the lifetime of an ASP.Net application? Is each request a separate execution? Is anything persisted from request to request?

As you can see, I don't have a good understanding of when/how classes are loaded by the .Net runtime, and I was having trouble articulating the right Google query for this. If someone can point me to general documentation on the subject, I would be most appreciative.

+1  A: 
  1. For the most part, yes. But you have no control over when the static constructor is executed, except for the guarantee that it will be executed prior to it being used for the first time and that it will be thread-safe.
  2. No. Only the first time it's accessed, once per application domain.
  3. The lifetime of a .Net app depends on IIS application pool settings and the stability of the application. There is an IIS setting that can force an application to recycle which may cause the application to restart. And of course the application can also crash, such as by an unmanaged library, which too will cause a restart.
jojaba
This may also be of use. http://stackoverflow.com/questions/7095/is-the-c-static-constructor-thread-safe
jojaba
What happens if an exception is thrown and is not caught?
Breck Fresen
In a typical .NET application an exception will kill the process. An ASP.NET application picks up requests through the pipeline and handle the exception without restarting the entire pool. Therefore static objects will maintain their state. More info on the pipeline http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp
jojaba