Why recycle at all?
Normally you don’t need to. Recycling the application pool
simply release the resources held by the current application pool stop the w3p
process and start another one for the same application pool. Supposable it
release memory created by memory leaks, but if you don’t have memory leak, like
all applications are supposed to, this will just make your site perform slower when
the recycle occurs. Here is some description and you can find more like this:
Why Visual Studio recycle IIS on deploy?
When you add solution to SharePoint you are basically adding
a “wsp” package that contains in it all definitions and dll libraries that
where compiled and bundled up in order for share point to use it. But the
application pool process may already use a previous version of the dll
libraries deployed with a previous version of the package and the recycle of
the application pool clear all held instances and use the latest content
delivered by the package. Also recycling iis pool before the deploy itself may help
speed it up.
Here is some information on the deploy and release processes
in SharePoint:
http://gokanx.wordpress.com/2013/10/24/release-distribution-process-on-sharepoint-gotchas/
Recycle app pool with code
The idea is really simple you pass SPApplicationPool instance find the server location,
retrieve an instance of the DirectoryEntry and start the recycle process:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.SharePoint.Administration; | |
using System; | |
using System.DirectoryServices; | |
using System.Linq; | |
namespace Classes | |
{ | |
internal static class ApplicationPool | |
{ | |
public static void RecycleAppPull(SPApplicationPool app) | |
{ | |
// find front end server | |
SPServerCollection servers = app.Farm.Servers; | |
SPServer server = null; | |
if (servers.Count == 1) | |
{ | |
server = servers.FirstOrDefault(); | |
} | |
else | |
{ | |
server = servers.FirstOrDefault(s => s.Role.ToString().Equals("WebFrontEnd")); | |
} | |
// if server is not found do not continue | |
if (server == null) return; | |
// get the DirectoryEntry instance of the application pool | |
DirectoryEntry dentry = ApplicationPool.GetIIS(server.Name, app.Name); | |
// recycle the application pool | |
if (dentry != null && DirectoryEntry.Exists(dentry.Path)) | |
{ | |
dentry.Invoke("Recycle"); | |
dentry.Dispose(); | |
} | |
else | |
throw new Exception("Application pool '" + app.Name + "' does not exists!"); | |
} | |
public static DirectoryEntry GetIIS(string service, string pool) | |
{ | |
DirectoryEntry root = null; | |
try | |
{ | |
root = new DirectoryEntry("IIS://" + service + "/W3SVC/AppPools/" + pool); | |
} | |
catch | |
{ | |
return null; | |
} | |
return root; | |
} | |
} | |
} |