Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)

This is the seventh in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.

I’m going to switch from discussing new VS 2010 tooling features and instead do a few posts covering a few new runtime features (don’t worry – I’ll come back to a lot more VS features, I’m just trying to mix things up a bit).

Today’s post covers a small, but nice, new feature that you can now optionally take advantage of with ASP.NET 4 - the ability to automatically startup and proactively initialize a web application without having to wait for an external client to hit the web server.  This can help you provide a faster response experience for the first user who hits the server, and avoids you having to write custom scripts to “warm up” the server and get any data caches ready.  It works with all types of ASP.NET applications – including both ASP.NET Web Forms and ASP.NET MVC based applications.

Auto-Start Web Applications with ASP.NET 4

Some web applications need to load large amounts of data, or perform expensive initialization processing, before they are ready to process requests.  Developers using ASP.NET today often do this work using the “Application_Start” event handler within the Global.asax file of an application (which fires the first time a request executes).  They then either devise custom scripts to send fake requests to the application to periodically “wake it up” and execute this code before a customer hits it, or simply cause the unfortunate first customer that accesses the application to wait while this logic finishes before processing the request (which can lead to a long delay for them).

ASP.NET 4 ships with a new feature called “auto-start” that better addresses this scenario, and is available when ASP.NET 4 runs on IIS 7.5 (which ships with Windows 7 and Windows Server 2008 R2).  The auto-start feature provides a controlled approach for starting up an application worker process, initializing an ASP.NET application, and then accepting HTTP requests.

Configuring an ASP.NET 4 Application to Auto-Start

To use the ASP.NET 4 auto-start feature, you first configure the IIS “application pool” worker process that the application runs within to automatically startup when the web-server first loads.  You can do this by opening up the IIS 7.5 applicationHost.config file (C:\Windows\System32\inetsrv\config\applicationHost.config) and by adding a startMode=”AlwaysRunning” attribute to the appropriate <applicationPools> entry:

<applicationPools>

     <add name="MyAppWorkerProcess" managedRuntimeVersion="v4.0" startMode="AlwaysRunning" />

</applicationPools>

If you load up the Windows task manager, click the “show processes from all users” checkbox, and then hit save on a startMode attribute change to the applicationHost.config file, you’ll see a new “w3wp.exe” worker process immediately startup as soon as the file is saved.

A single IIS application pool worker process can host multiple ASP.NET applications.  You can specify which applications you want to have automatically start when the worker process loads by adding a serviceAutoStartEnabled="true" attribute on their <application> configuration entry:

<sites>

     <site name="MySite" id="1">

          <application path="/" serviceAutoStartEnabled="true" serviceAutoStartProvider="PreWarmMyCache" />

     </site>

</sites>

<serviceAutoStartProviders>

     <add name="PreWarmMyCache" type="PreWarmCache, MyAssembly" />

</serviceAutoStartProviders>

The serviceAutoProvider="PreWarmMyCache" attribute above references a provider entry within the config file that enables you to configure a custom class that can be used to encapsulate any "warming up" logic for the application.  This class will be automatically invoked as soon as the worker process and application are preloaded (before any external web requests are received), and can be used to execute any initialization or cache loading logic you want to run before requests are received and processed:

public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient {

    public void Preload(string[] parameters) {

        // Perform initialization and cache loading logic here...

    }

}

IIS will start the application in a state during which it will not accept requests until your "warming up" logic has completed.  After your initialization code runs in the Preload method and the method returns, the ASP.NET application will be marked as ready to process requests. 

You can optionally combine the new auto-start "warming up" feature with the load-balancing capabilities of the IIS7 Application Request Routing (ARR) extension, and use it to signal to a load-balancer once the application is initialized and ready to accept HTTP traffic – at which point the server can be brought into the web farm to process requests.

Summary

The new "auto start" feature of ASP.NET 4 and IIS 7.5 provides a well-defined approach that allows you to perform expensive application startup and pre-cache logic that can run before any end-users hit your application.  This enables you to have your application "warmed up" and ready from the very beginning, and deliver a consistent high performance experience.

Hope this helps,

Scott

P.S. In addition to blogging, I have been using Twitter more recently to-do quick posts and share links.  You can follow me on Twitter at: http://www.twitter.com/scottgu (@scottgu is my twitter name)

36 Comments

  • Great post Scott. Keep them coming.

  • Will this be available in ASP.NET MVC also? or is it just for webforms ASP.NET?

  • @Phil,

    >>>>>>> Will this be available in ASP.NET MVC also? or is it just for webforms ASP.NET?

    This works for all types of ASP.NET application - both WebForms and MVC.

    Hope this helps,

    Scott

  • Nice :D this can only make life easyer.

    Does this mean that the application is now always running and that the application does not time out?

    Steve

  • @sjnaughton,

    >>>>>>>> Nice :D this can only make life easyer. Does this mean that the application is now always running and that the application does not time out? Steve

    Yep - that means the application is always running. You can still choose to auto-recycle the worker processes from time to time. When you do that, though, the app will immediately restart and your warm up code will execute (unlike today - where you have to wait for the next request to-do that).

    Thanks,

    Scott

  • If I set startMode="AlwaysRunning" does this mean the web app will 'never' shut down and will always be kept running, even with no traffic hitting the site for a long period (unless of course it's manually shut down, or server is switched off/crashes etc.)?

    The reason I ask is because I like to run background threads/services on the IIS ASPNET worker process instead of using Windows Services (we deal with clients with lots of security restrictions on their servers which makes running a Windows Service difficalt or impossible). Normally I have to devise something that hits the website periodically to keep the ASPNET worker process alive and stop it from shutting down.

  • @Dominic Pettifer,

    >>>>>>>>>> If I set startMode="AlwaysRunning" does this mean the web app will 'never' shut down and will always be kept running, even with no traffic hitting the site for a long period (unless of course it's manually shut down, or server is switched off/crashes etc.)? The reason I ask is because I like to run background threads/services on the IIS ASPNET worker process instead of using Windows Services (we deal with clients with lots of security restrictions on their servers which makes running a Windows Service difficalt or impossible). Normally I have to devise something that hits the website periodically to keep the ASPNET worker process alive and stop it from shutting down.

    This should mean that the application and worker process is always running - so I think that does indeed handle your scenario well for you.

    Hope this helps,

    Scott

  • THIS
    IS
    AWESOME!!!

  • BTW what will 'parameters' parameter in the

    public void Preload(string[] parameters) method

    contain?

  • While developing a full-fledge help system I needed to index/re-index help content whenever the application starts. Using threads, I didn't keep user waited for the first call, but he would be displayed that something in background is happening and you will have to visit the page again in 2 mins or so.

    This new feature will serve my scenario very well. One question to scott - how you guys get such requirements - from customers or just your team's brain child?

    Anyways, good to go with it. Thanks.

  • "IIS will start the application in a state during which it will not accept requests until your "warming up" logic has completed"

    Risky business... what happens if your Preload method throws an exception?

  • Is this really an ASP.NET feature? Seems more like a feature of IIS7.5, right? In other words, couldn't I use this same feature for a WCF application running under WAS?

    Thanks,
    Drew

  • Nice post.

    Does this mean that if you throw a new DLL in the bin of a web site that existing users on ASP.NET Worker Processes that use the old DLL will continue to serve up pages until the new ASP.NET Worker Process (that uses the new DLL) is done compiling?

    Thanks,
    Seth

  • Scott, what about a Web Hosting company, with thousands of sites on a single server?

    Does Warming Up and AutoStarting take up a considerable amount of memory? If so, any shared-hosting application probably cannot benefit from this, am I correct?

  • hi I want to know how to change template at runtime . actually i am defined two temlates for my buton and i want to change it on button click, how to do this??????

  • @Mike,

    >>>>>>>> Risky business... what happens if your Preload method throws an exception?

    If your preload method throws an unhandled exception we'll shutdown the worker process. It will be activated on demand by the next web request (like it is today). If that continues to fail then after a certain number of failed requests IIS will mark the application as having a problem and stop sending requests to it for awhile (the duration is configurable) before trying again later.

    I don't think the preload method is any more dangerous or risky compared to loading data and warming up on first request. The reality is that if you have unhandled exceptions being thrown in your application anywhere you have a problem.

    Hope this helps,

    Scott

  • @Drew Marsh,

    >>>>>>>>> Is this really an ASP.NET feature? Seems more like a feature of IIS7.5, right? In other words, couldn't I use this same feature for a WCF application running under WAS?

    It is partly an IIS feature (loading the worker process proactively and activating the application proactively). ASP.NET 4 then does the work to call the PreLoad method and setup the application.

    WCF running under WAS uses IIS and ASP.NET for its hosting model - so it will benefit too from this feature.

    Thanks,

    Scott

  • @Steve,

    >>>>>>>>> Scott, what about a Web Hosting company, with thousands of sites on a single server? Does Warming Up and AutoStarting take up a considerable amount of memory? If so, any shared-hosting application probably cannot benefit from this, am I correct?

    In shared hosting scenarios involving lots of customers on a single box, the typical configuration scenario is to pack customers on the machine and rely on worker processes restarting periodically to avoid using up all the memory. Most shared host business models rely on the fact that 90% of the customers don't get too much traffic and so don't need to be loaded simultaneously. In those scenarios (lots of inactive customers) you wouldn't want to use this feature - and instead rely on the applications to spin up and down automatically.

    Note that this feature is configured at the applicationHost.config level as opposed to the application level so that the hoster or machine admin can decide the policy - and so a shared host customer can't turn it on without the hoster agreeing.

    Hope this helps,

    Scott

  • Scott, what happens when I'm updating the assemblies in the \bin directory? Will it restart and warm up for each assembly that gets touched?

  • that is really cool :) what is not cool however is if we have to get 2008R2 in order to get this feature.. ive never understood why iis has to be so tightly coupled with the os..

    changeing a server os is a huge investment in terms of time and effort (atleast in my semi small company) also, old versions of iis periodically have bugs that newer versions dont, but because you cant simply upgrade iis, these servers are still around.. :/

    my number one feature request for iis is to be able to run it on older servers.. even if some stuff is not available, like super high speed kernel caching and such

  • Scott,

    I just wanted to compliment you on your posts. They are always so helpful and informative. Thanks and keep em coming!

  • Scott, how does this play with App_Offline.htm, if at all? It would be nice if it was possible to have IIS serve up a static page while it was warming up to let the visitor know what's going on (if the first visitor happens to hit you while you are still warming up).

    Thanks!
    -Michael

  • What all trigger the prewarm thing to kick-in?
    eg1: Application pool restart(?)
    eg2: others?

  • Its an awesome feature... I would love to c it in action...

  • Will Hosting Server give this Permission to start all the application that it Hosts?
    Load of memory?

  • Nice Post Scott.
    Can you give any idea about upcoming Vs2010 beta 2 or VS2010 RC release date?

  • I think it's a great feature for developers. But the hard task is to convince Server Administrator's to modify the configuration file and that it won't affect server performance negatively.

  • Ahh.. I've been missing this one for some time!

    Looking forward to visual studio 2010 :-)

    //Olav

  • Thanks a lot of your useful post.

  • It is very great! most of our user think its the biggest disadvantage of the performance of the first time to load our page.

  • Thanks a lot for the post Scot

  • Great feature, may look like something little or simpler, but its great for user experience :).

    Excelente !

  • Gr8 Post Scott .... Let me know all about ASP.NET 4

  • Thanks for the post Scott. Would it make sense to use this feature to start a background process that needs to be running 24/7?

    Problem I have now is that everytime the application is restarted, the thread won't be restarted until the first user hits the page.

  • Auto starting web-apps, thank God! This has always been a peeve of mine, glad its finally being addressed without having to write any special warming up components.

  • Wow thats great, i am following you on Twitter. Visual studio 2010 is great product!

Comments have been disabled for this content.