簡體   English   中英

使用Thread.Sleep時啟動.NET Windows服務時出現問題

[英]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.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;
}

衛生署。 我剛剛意識到我在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM