Home  »  Articles  »  ASP.Net  »

How to restart your application pool programatically

 Posted By : Manoranjan SahooPosted Date : 17/05/2015 07:38:28 PM Category : ASP.Net Points : 10 (Rs 2.00)

In general, we use cache to improve our website's performance. Caching is really useful when we are frequently displaying data which rarely requires changes. But, sometime our website needs an immediate changes in all cache entries and we have no option to manually do the IIS reset or change the contents of web.config file to clear all the cache. 

Here I am sharing a code sample which will help you to solve this issue :-
namespace DotNetSquare.Utilities
{
    public static class Utility
    {
        public static bool RestartAppPool()
        {
            //First try killing your worker process
            try
            {
                //Get the current process
                Process process = Process.GetCurrentProcess();
                // Kill the current process
                process.Kill();
                // if your application have no rights issue then it will restart your app pool
                return true;
            }
            catch (Exception ex)
            {
                //if exception occoured then log exception
                Logger.Log("Restart Request Failed. Exception details :-" + ex);
            }
 
            //Try unloading appdomain
            try
            {
                //note that UnloadAppDomain requires full trust
                HttpRuntime.UnloadAppDomain();
                return true;
            }
            catch (Exception ex)
            {
                //if exception occoured then log exception
                Logger.Log("Restart Request Failed. Exception details :-" + ex);
            }
 
            //Now try to do with web.config file change. Get the path of web.config
            string webConfigPath= HttpContext.Current.Request.PhysicalApplicationPath + "\\web.config";
            try
            {
                //Change the last modified time and it will restart pool
                File.SetLastWriteTimeUtc(webConfigPath, DateTime.UtcNow);
                return true;
            }
            catch (Exception ex)
            {
                //if exception occoured then log exception
                Logger.Log("Restart Request Failed. Exception details :-" + ex);
            }
 
            //Still no hope, you have to do something else.
            return false;
        }
    }
}

To implement above case you have to create a aspx page. for example :- RestartApplication.aspx. 

Thank you.





For More Details Visit : http://zeeshanumardotnet.blogspot.jp/2011/04/how-to-restart-your-web-application.html
Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.