How to restart an ASP.NET web application

One of the problems that I encounter so often is need to refresh an ASP.NET website. Many times we make some changes in website’s data and need the website act on these new data. But unfortunately this does not take effect, because ASP.NET worker process is not going to read data from beginning.

One of examples that I recently encountered was a custom Sitemap provider. This provider read data from database and builds Sitemap based on it. But because of avoiding dead lock and avoiding building Sitemap with each request, the provider uses a `lock` and checks if the Sitemap tree has been built before, and if yes it just returns a cached version of it. So even data is changed, Sitemap will not informed about changes until an `IISREST`. IISRESET is not a good idea because you have not access to it in remote hosts. And IISRESET is a very expensive operations. It shut downs all websites.

Best way to force refreshing an ASP.NET website is to restart it internally. Peter Bromberg in an article describes some ways for restarting an ASP.NET website. Here is one of those ways that I used in my application happily:

public static void RestartWebSite()
{
System.Web.HttpRuntime.UnloadAppDomain();

//Loading a page after unloading is necessary
//due to start the application again.
HttpContext.Current.Response.Redirect("~/Default.aspx");
}