我的Windows服务短暂运行,然后停止(没有错误消息)。
我在Windows服务的Program.cs中有这段代码:
static class Program
{
[STAThread]
static void Main()
{
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
Console.ReadLine();
#endif
}
}
这里的断点:
var rrs = new RoboRprtrService();
...被命中(当前定义了DEBUG常量),调用" InitializeComponent()"在我的ServiceBase类中,如下所示:
public partial class RoboRprtrService : ServiceBase
{
private Timer timer;
private bool operationIsRunning;
public RoboRprtrService()
{
InitializeComponent(); // <= Breakpoint here; is reached
}
protected override void OnStart(string[] args)
{
ConfigureService(); // <= Breakpoint here, not hit
}
public void ConfigureService()
{
const int ONE_HOUR = 3600000;
timer = new Timer { Interval = 50000 };
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
if (operationIsRunning) return; // <= Breakpoint here, not hit
operationIsRunning = true;
timer.Elapsed -= timer_Tick;
try
{
RoboRprtrLib.WriteToLog("Timer tick event has occurred");
RoboRprtrLib.GenerateAndSaveDueReports();
operationIsRunning = false;
}
finally
{
timer.Elapsed += timer_Tick;
}
}
protected override void OnStop()
{
timer.Enabled = false;
RoboRprtrLib.WriteToLog("RoboRprtrService has stopped");
}
}
当我步骤(F11)进入InitializeComponent()时;在构造函数中,它将我带到这个机器生成的代码:
namespace RoboReporterService
{
partial class RoboRprtrService
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
...(进入InitializeComponent()方法)然后服务停止。
为什么我的服务无法生存?#34;
作为旁注,此项目的属性在“应用程序”选项卡上显示此输出类型为&#34; Windows应用程序&#34 ;;不应该是&#34;班级图书馆&#34;?
注意:如果我从Service类中的ConfigureService()方法调用代码,如下所示:
public void ConfigureService()
{
const int ONE_HOUR = 3600000;
timer = new Timer { Interval = 50000 };
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
operationIsRunning = true;
RoboRprtrLib.GenerateAndSaveDueReports();
operationIsRunning = false;
}
...它运行;但随后服务停止,并且永远不会到达timer_Tick()处理程序,即使它已连接到ConfigureService()