[英]Problems starting a .NET Windows Service when using Thread.Sleep
我已经创建了一个.NET Windows服务,并从bin / debug文件夹安装了调试版本(是的,我知道这不是一个好方法,但是我只想能够对其进行测试并附加调试器)。
该服务基本上以无限循环运行,检查FTP目录中的文件,对其进行处理,休眠一分钟,然后循环。
当我尝试启动服务时,出现以下错误
Error 1053: The service did not respond to the start or control request in a timely fashion
经过进一步检查,服务将完成第一个循环,然后在第一个线程睡眠期间超时。 因此,我对应该如何启动服务感到有些困惑。 是我(缺乏)对线程的理解导致了这一点?
我的起始代码是
protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Service started");
ThreadStart ts = new ThreadStart(ProcessFiles);
workerThread = new Thread(ts);
workerThread.Start();
}
在ProcessFiles函数中,完成循环后,我只需
eventLog.WriteEntry("ProcessFiles Loop complete");
Thread.Sleep(new TimeSpan(0,1,0));
当我检查事件日志时,“ ProcessFiles循环完成”日志在那里,但这是服务超时且无法启动之前的最后一个事件。
有人可以解释我在做什么错吗?
我在ProcessFiles函数中处理循环的方式如下
while (!this.serviceStopped)
{
// Do Stuff
eventLog.WriteEntry("ProcessFiles Loop complete");
Thread.Sleep(new TimeSpan(0,1,0));
}
干杯
斯图尔特
当我检查事件日志时,“ ProcessFiles循环完成”日志在那里。
您可能有一个文件处理代码,直到服务超时才返回。 您尝试在间隔后执行一些任务,最好使用System.Timers.Timer或System.Windows.Forms.Timer而不是循环来重复执行某些任务。
要测试是否是循环问题,可以使用sleep语句将循环限制为单次迭代,并检查服务是否启动。
protected override void OnStart(string[] args)
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 60000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false;
// Put file processing code here.
aTimer.Enabled = true;
}
卫生署。 我刚刚意识到我在Main Program方法中使用了以下代码,以便能够在VS中进行调试。 显然,当我安装调试版本时,它在主线程上设置了无限超时。 删除调试代码解决了该问题。
#if DEBUG
AdvanceLinkService myService = new AdvanceLinkService();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new AdvanceLinkService()
};
ServiceBase.Run(ServicesToRun);
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.