Wednesday 30 June, 2010

Restart ASP.NET Application Programatically

A lot of developers are asking how to restart the ASP.NET application or recycle the ASP.NET process without the need to modify the content of web.config file or changing its name.

You can use the HttpRuntime.UnloadAppDomain() which will terminate the application and of course remove all the session objects for all users the next time a request is being received.

Demonstration:

Create a dummy web application, drag and drop two buttons. and use some like below

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if(!IsPostBack)

Session.Add("ASP","hello");

}

private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
HttpRuntime.UnloadAppDomain();
}

private void Button2_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
}


When you click Button2, you will have object reference not set to an instance of an object error which indicates that Session["ASP"] is equal to null.

Hope this helps

No comments:

Post a Comment