Sunday, 13 November 2011

Manage IIS Application Pool from .Net C# code

  .Net framework provides a very easy-to-use API wrapper class, ServerManager, to help manage IIS system from any .Net application using either C# or VB.net. Below C# code snippet demonstrates how to restart/recycle a given AppPool in IIS.
     
    public void RestartAppPool(string appPool)
        {
            try
            {
                logger.Info("Restarting app pool: " + appPool);

                // Recycle app pool
                using (var manager = new ServerManager())
                {
                    var pool = manager.ApplicationPools[appPool];

                    if (pool != null) 
                    {
                        Process process = null;

                        if (pool.WorkerProcesses.Count > 0)
                        {
                            process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                        }

                        if (pool.State == ObjectState.Stopped)
                            pool.Start();
                        else
                            pool.Recycle();

                        // clean up any worker thread created by app pool
                        if (process != null)
                        {
                            while (!process.HasExited)
                            {
                                Thread.Sleep(10);
                            }

                            process.Dispose();
                        }
                    }
                }

                //logger.Info("Successfully restarted app pool: " + appPool);
            }
            catch (Exception ex)
            {
               // logger.Error("Restart app pool error: " + ex);
            }
        }
 

4 comments:

  1. "Enhance your data visualization skills with our comprehensive tableau online training , designed for beginners and professionals alike."

    ReplyDelete
  2. "Enhance your data analytics skills with power bi classes designed for beginners and professionals alike. Learn to visualize, analyze, and transform data into actionable insights efficiently."
    If you want, I can create 3–5 alternative catchy versions as well.

    ReplyDelete
  3. "Boost your career with our comprehensive salesforce development training designed for beginners and professionals alike."

    ReplyDelete