我创建了一项服务,该服务对一个数据库执行许多检查,并使用检查结果更新另一个数据库。 但是,每次尝试启动服务时都会出现主题错误。 我能够在调试器中成功运行该服务,一切正常。 我也调整了这里描述的超时http://support.microsoft.com/kb/824344无济于事。 下面是我的Program.cs文件:
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时将timer.Interval调整为3分钟。 当我尝试启动该服务时,我可以看到它将事件报告给OnTimer方法中存在的日志文件。
这是我第一次尝试编写服务,但我希望这项服务能够被认为是&#34;运行&#34;一旦它达到这行代码:
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
当我在调试器中运行它时,它总是在触发OnTimer之前到达这行代码。我没有正确更新服务状态吗?
[编辑] 在查看事件日志后,即使服务管理器抛出主题错误,服务仍会继续运行OnTimer事件。但是,一旦完成OnTimer方法,服务就会停止。
答案 0 :(得分:0)
您不必负责更新服务状态 - 当您在OnStart(...)
内时服务状态开始待处理,当您退出方法时,它的状态将更改为运行。我从未尝试手动更新服务状态但我认为这会导致该方法一直闲逛直到超时。
编辑:似乎main()作为项目的一部分导致了服务的错误条目注册。