我創建了一個服務,該服務對一個數據庫執行多次檢查,並使用檢查結果更新另一個數據庫。 但是,每次嘗試啓動服務時都會出現主題錯誤。 我能夠在調試器中成功運行該服務,並且一切正常。 我也調整了這裏描述的超時時間http://support.microsoft.com/kb/824344無濟於事。 下面是我的Program.cs文件:Visual Studio C#:該服務沒有及時響應啓動或控制請求
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內部,間隔爲3分鐘。 當我嘗試啓動該服務時,我可以看到它將事件報告給OnTimer方法中存在的日誌文件。
這是我在寫一個服務的第一次嘗試,但我沒有料想到會被認爲是服務「運行」,一旦它擊中這行代碼:當我在調試器中運行
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
,它在觸發OnTimer之前總是到達這一行代碼。我沒有正確更新服務狀態嗎?
[編輯]回顧事件日誌後,即使在服務管理器拋出主題錯誤後,服務仍然繼續運行OnTimer事件。但是,一旦完成一次OnTimer方法,服務就會停止。
您不需要手動對服務狀態執行任何操作。 'ServiceBase.Run'應該爲你處理所有的事情。 – 2014-09-03 12:56:52
我刪除了手動服務狀態更新並在Main方法中調用ServiceBase.Run,但這不能解決問題。 public static void Main() {System.ServiceProcess.ServiceBase.Run(new Service1()); }' – jaredcnance 2014-09-03 13:19:08