Difference between Application_Start and Application_OnStart
Asked Answered
B

3

46

I'm in the process of adding ASP.NET MVC code to a preexisting ASP.NET Webforms project. The various tutorials suggest adding routing to a method called from Application_Start() in Global.asax. My Global.asax already has an Application_OnStart(Object,EventArgs) method with some setup code.

If I try to have both Start and OnStart, the OnStart doesn't get called (and the setup fails, causing errors). It looks like I have to choose one or the other.

My question is: which one should I be using? What is the difference between them? Are they called at different times?

(Note: at the time of this writing, the top three Google hits are useless and/or misleading. I'm hoping Stack Overflow can fix that.)

Brien answered 13/1, 2010 at 17:1 Comment(0)
C
86

In classic (legacy) ASP, there are a handful of special function names that, if defined in your global.asa file, will be run at specified points during the application lifecycle. These are defined as:

  • Application_OnStart - runs once, when your application receives the first HTTP request and immediately before any .ASP files are processed.
  • Application_OnEnd - runs once, during application shutdown, after all requests have been processed.
  • Session_OnStart - runs at the start of each unique user session. If a user/client has cookies disabled, this runs for every request because ASP never detects the session cookie identifying an existing session.
  • Session_OnEnd - (theoretically!) runs each time a user session expires. Good luck with this.

These are basically hard-wired into the classic ASP runtime - you can't change them, and you can't attach any other methods to these events.

In ASP.NET, there's a thing called AutoEventWireup that uses reflection to find methods conforming to particular naming conventions, and runs those methods in response to matching events raised by the ASP.NET runtime. The most common example is the Page_Load method, which is automatically invoked in response to the Page class firing the Load event during the page lifecycle.

The same technique is used to attach handlers to application-level lifecycle events. It will look for methods named either ModuleName_EventName or ModuleName_OnEventName, taking either no parameters () or (object sender, EventArgs e)

Here's the fun part - if you define more than one matching method, only the one that appears latest in the file will execute. (The last method wins, basically)

So if your global.asax.cs looks like this:

public class Global : System.Web.HttpApplication {
    protected void Application_Start() {
        Debug.WriteLine("A: Application_Start()");
    }

    protected void Application_Start(object sender, EventArgs e) {
        Debug.WriteLine("B: Application_Start(object sender, EventArgs e)");
    }

    protected void Application_OnStart() {
        Debug.WriteLine("C: Application_OnStart()");

    }
    protected void Application_OnStart(object sender, EventArgs e) {
        Debug.WriteLine("D: Application_OnStart(object sender, EventArgs e)");
    }
}

you'll see message D in your debug output; if you comment out the last method in that block, you'll see message C instead.

So - use whichever naming convention you like, but if you define more than one, only the one that appears last in your source file will be executed. I would personally stick with Application_Start(object sender, EventArgs e) since that's the signature generated by the Visual Studio project templates and most .NET design/coding tools.

Cornet answered 13/1, 2010 at 18:18 Comment(4)
Great explanation, especially with the different method signatures.Brien
I have a question about this explanation. When you say "runs once, before any .ASP files are processed" does that mean that the process runs when the server is started or at the beginning of each HTTP connection? If the former, then would it be possible to instantiate a singleton that can run a background process that should be ran through the life of the application?Aprilaprile
@Aprilaprile The application doesn't until it receives an HTTP request. When this request arrives, IIS will start the application process, run any Application_Start events, and THEN process the incoming request. It's common for deployment scripts to deploy a new version of the app and then make an HTTP request to start up the application immediately - especially if Application_Start takes several seconds tom complete. Better to do this upfront than penalise the unlucky user who happens to be your first visitor after a deployment.Cornet
@Aprilaprile As for background processes - it's possible but really not recommended. Take a look at haacked.com/archive/2011/10/16/… and hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx for more discussion around how to run background tasks as part of an ASP.NET application.Cornet
I
12

According to Microsoft docs on the ASP.Net app life cycle you should be using the Application_Start method inside the global.asax file:

Application_Start: Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.

W3 schools describes more about Application_OnStart in ASP (legacy ASP?). This method goes in Global.asa, not Global.asax.

Application_OnStart: The Application_OnStart event occurs before the first new session is created (when the Application object is first referenced). This event is placed in the Global.asa file.

See the comments to this answer which suggest Application_OnStart is for legacy ASP, whereas Application_Start is for ASP.NET.

Indigotin answered 13/1, 2010 at 17:9 Comment(1)
I'm guessing that OnStart works in ASP.NET/Global.asax just as a backwards-compatibility move with legacy ASP. I've flipped my app to Start with no ill effects thusfar. Thanks!Brien
L
6

Application_OnStart:

The Application_OnStart function is called before any .asp files are processed — before any text or graphics are rendered and sent to the user's browser. Within this function, the following call to the CreateObject method on the Active Server Pages Server object creates the CDO Rendering Library RenderingApplication object. If this call succeeds, the objRenderApp variable contains a pointer to the new object.

All references I've been able to find refer to .asp pages

Application_Start

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

This page refers to .aspx pages. So as you are using MVC and mention global.asax this is the one you should be using.

Lonnielonny answered 13/1, 2010 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.