【问题标题】:Problems starting a .NET Windows Service when using Thread.Sleep使用 Thread.Sleep 时启动 .NET Windows 服务时出现问题
【发布时间】:2013-05-27 11:16:01
【问题描述】:

我创建了一个 .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 Loop Complete' 日志在那里,但这是服务超时之前的最后一个事件并且无法启动。

谁能解释我做错了什么?

编辑

我在 ProcessFiles 函数中处理循环的方式如下

while (!this.serviceStopped)
{
    // Do Stuff
    eventLog.WriteEntry("ProcessFiles Loop complete");
    Thread.Sleep(new TimeSpan(0,1,0));
}

干杯

斯图尔特

【问题讨论】:

  • 你能发布更多你的代码吗?到目前为止,它似乎是正确的......

标签: c# multithreading windows-services


【解决方案1】:

当我检查事件日志时,'ProcessFiles Loop Complete' 日志在那里...

您可能有一个文件处理代码,该代码在服务超时之前不会返回。您尝试在间隔后执行某些任务,您最好使用System.Timers.TimerSystem.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;
}

【讨论】:

  • 我去掉了循环,甚至去掉了超时,但是还是出现了同样的错误。我会尝试使用工作线程的方法
  • 文件处理代码需要多长时间?由于您必须在间隔后进行文件处理,因此我会使用计时器。
  • 看我的回答。小学生错误!不过,您的 cmets 处理间隔很有用
【解决方案2】:

哦。我刚刚意识到我的主程序方法中有以下代码,我用它来在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 2011-04-22
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多