我已经创建了一个 .NET Windows 服务并从 bin/debug 文件夹安装了调试版本(是的,我知道这不是一个好方法,但我只是希望能够测试它并附加调试器)。
该服务基本上以无限循环的方式运行,检查 FTP 目录中的文件,处理它们,休眠一分钟,然后循环。
当我尝试启动服务时,出现以下错误
Error 1053: The service did not respond to the start or control request in a timely fashion
经过进一步检查,服务正在完成第一个循环,然后在第一个线程 sleep 期间超时。因此,我对应该如何启动该服务有些困惑。是我(缺乏)对线程的理解导致了这种情况吗?
我的起始代码是
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 Loop Complete”日志就在那里,但这是服务超时且无法启动之前的最后一个事件。
有人可以解释一下我做错了什么吗?
编辑
我在 ProcessFiles 函数中处理循环的方式如下
while (!this.serviceStopped)
{
// Do Stuff
eventLog.WriteEntry("ProcessFiles Loop complete");
Thread.Sleep(new TimeSpan(0,1,0));
}
干杯
斯图尔特
最佳答案
当我检查事件日志时,“ProcessFiles Loop Complete”日志就在那里......
您可能有一个用于文件处理的代码,该代码在服务超时之前不会返回。您尝试在间隔后执行某些任务,您最好使用 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;
}
关于c# - 使用 Thread.Sleep 时启动 .NET Windows 服务时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771958/