获取服务以在Azure辅助角色中运行

我有一个Windows服务,我需要迁移到Azure作为工作者角色。 在我的Azure解决方案中,一切都很好。 但是,当我上传所有内容时,只会启动Web角色。 工作者角色实例在以下两种状态之间卡住循环而不启动。

  • 等待角色开始……
  • 稳定角色……

由于实例未能启动,我怀疑我的问题出现在我的WorkerRole.cs代码中。 您将在下面找到该代码。 我还提供了服务代码,以防它与问题相关。 我做错了什么?

这是我的WorkerRole.cs文件:

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.StorageClient; using System.ServiceProcess; namespace SBMWorker { public class WorkerRole : RoleEntryPoint { public override void Run() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); //Thread.Sleep(Timeout.Infinite); } } } 

这是我的Service1.cs代码:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using Lesnikowski.Mail; namespace SBMWorker { public partial class Service1 : ServiceBase { private System.Timers.Timer mainTimer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { try { // config the timer interval mainTimer = new System.Timers.Timer(foo.Framework.Configuration.SecondsToWaitBeforeCheckingForEmailsToProcess * 1000); // handling mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(mainTimer_Elapsed); // startup the timer. mainTimer.Start(); // log that we started foo.Framework.Log.Add(foo.Framework.Log.Types.info, "SERVICE STARTED"); } catch (Exception ex) { try { foo.Framework.Log.Add(ex, true); } catch{throw;} // make sure the throw this so the service show as stopped ... we dont want this service just hanging here like // its running, but really just doing nothing at all throw; } } protected override void OnStop() { if (mainTimer != null) { mainTimer.Stop(); mainTimer = null; } // log that we stopped foo.Framework.Log.Add(foo.Framework.Log.Types.info, "SERVICE STOPPED"); } void mainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { mainTimer.Stop(); bool runCode = true; if (runCode) { try { // call processing foo.Framework.EmailPackageUpdating.ProcessEmails(); } catch(Exception ex) { try { // handle error foo.Framework.Log.Add(ex, false); } catch { throw; } } } mainTimer.Start(); } } } 

我认为问题的根源在于您基本上无法以编程方式在Azure角色中安装服务。 您需要使用.cmd启动脚本和InstallUtil来正确安装服务,然后您可以从脚本或代码中启动它(出于执行顺序原因,通常首选脚本)。

这是一篇关于如何做到这一点的博客文章: http : //blogs.msdn.com/b/golive/archive/2011/02/11/installing-a-windows-service-in-a-worker-role.aspx

这是另一篇博文,它采用了一种不同的方法(创建一个执行安装的.Net应用程序,但同样作为启动脚本的一部分): http : //www.bondigeek.com/blog/2011/03/25/runninginstalling -a窗口服务function于一个-Azure的网络角色/

希望有所帮助