我创建了一个服务,该服务对一个数据库执行多次检查,并使用检查结果更新另一个数据库。 但是,每次尝试启动服务时都会出现主题错误。 我能够在调试器中成功运行该服务,并且一切正常。 我也调整了这里描述的超时时间http://support.microsoft.com/kb/824344无济于事。 下面是我的Program.cs文件:Visual Studio C#:该服务没有及时响应启动或控制请求
namespace PlantMonitor
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#else
var service = new Service1();
service.StartUp(); //Make the method public in order to Debug
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
}
}
,这里是我的Service1.cs文件:
namespace PlantMonitor
{
public partial class Service1 : ServiceBase
{
//declare the SetServiceStatus function by using platform invoke
[DllImport("advapi32.dll", SetLastError = true)]
.
.
.
public void StartUp()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
//startup stuff
// Update the service state to Start Pending.
ServiceStatus serviceStatus = new ServiceStatus();
serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
serviceStatus.dwWaitHint = 180000;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
//ConnectionState
eventLog1.WriteEntry("In OnStart");
// Set up a timer to trigger every minute.
timer.Interval = 10000; // 10 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
//Confrim Timer success
eventLog1.WriteEntry("Timer Success");
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
基本上,我设置定时器为10秒最初开始主的第一次迭代包含在OnTimer中的代码,并调整计时器。一旦我进入OnTimer内部,间隔为3分钟。 当我尝试启动该服务时,我可以看到它将事件报告给OnTimer方法中存在的日志文件。
这是我在写一个服务的第一次尝试,但我没有料想到会被认为是服务“运行”,一旦它击中这行代码:当我在调试器中运行
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
,它在触发OnTimer之前总是到达这一行代码。我没有正确更新服务状态吗?
[编辑]回顾事件日志后,即使在服务管理器抛出主题错误后,服务仍然继续运行OnTimer事件。但是,一旦完成一次OnTimer方法,服务就会停止。
您不需要手动对服务状态执行任何操作。 'ServiceBase.Run'应该为你处理所有的事情。 – 2014-09-03 12:56:52
我删除了手动服务状态更新并在Main方法中调用ServiceBase.Run,但这不能解决问题。 public static void Main() {System.ServiceProcess.ServiceBase.Run(new Service1()); }' – jaredcnance 2014-09-03 13:19:08