在Azure WebRole上自动启动WCF

我在Azure(WebRole)上托管了一个WCF。 WCF做了很多后台任务并回复了一些请愿。

问题是如果WCF长时间没有收到任何请求(10小时或更长时间),应用程序池将在azure实例上回收,并且WCF任务将停止。 我做了一些调查,我可以启用一个AutoStartfunction来触摸machine.config,但这不是一个azure deploy的选项。

我可以在web.config中启用AutoStart或部署配置文件吗?

您可以在WebRole.cs中添加一些代码来修改应用程序池:

public class WebRole : RoleEntryPoint { public override void Run() { using (var serverManager = new ServerManager()) { var mainSite = serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"]; var mainApplication = mainSite.Applications["/"]; var mainApplicationPool = serverManager.ApplicationPools[mainApplication.ApplicationPoolName]; mainApplicationPool["autoStart"] = true; mainApplicationPool["startMode"] = "AlwaysRunning"; serverManager.CommitChanges(); } base.Run(); } public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. return base.OnStart(); } } 

注意:要使用ServerManager您需要:

  • 参考C:\ Windows \ system32 \ inetsrv \ Microsoft.Web.Administration.dll (或通过NuGet提供)
  • 在WebRole元素下的Service Definition中添加

虽然Sandrino的解决方案可能有用……这里的解决方案不需要Web角色在提升的安全模式下运行,并且还会强制应用程序在webrole启动时启动(在第一个用户访问站点之前)。 此解决方案还适用于不需要IIS 8的“应用程序初始化”function的旧版IIS / Windows Server。

只需添加一个包含以下内容的WebRole.cs:

 using System; using System.Net; using System.Net.Security; using System.Threading; using Microsoft.WindowsAzure.ServiceRuntime; namespace Website { public class WebRole : RoleEntryPoint { public override bool OnStart() { WarmUpWebsite("HttpIn"); return base.OnStart(); } public override void Run() { while (true) { WarmUpWebsite("HttpIn"); Thread.Sleep(TimeSpan.FromMinutes(1)); } } public void WarmUpWebsite(string endpointName) { // Disable check for valid certificate. On som sites live HTTP request are redirected to HTTPS endpoint. And when running on staging SSL the certificate is invalid. RemoteCertificateValidationCallback allowAllCertificatesCallback = (sender, certificate, chain, sslPolicyErrors) => true; ServicePointManager.ServerCertificateValidationCallback += allowAllCertificatesCallback; try { RoleInstanceEndpoint endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endpointName]; string address = String.Format("{0}://{1}:{2}", endpoint.Protocol, endpoint.IPEndpoint.Address, endpoint.IPEndpoint.Port); //This will cause Application_Start in global.asax to run new WebClient().DownloadString(address); } catch (Exception) { // intentionally swallow all exceptions here. } ServicePointManager.ServerCertificateValidationCallback -= allowAllCertificatesCallback; } } } 

积分转到: http : //weblogs.thinktecture.com/cweyer/2011/01/poor-mans-approach-to-application-pool-warm-up-for-iis-in-a-windows-azure-web- role.html

while(true)可以用Sandrino的方法替换,或者你可以禁用应用程序池空闲超时: http : //blog.smarx.com/posts/controlling-application-pool-idle-timeouts-in-windows-azure