的「輪詢」類將被從您所創建的輪詢線程使用,讓你有一些選擇第一服務應用。我可能會去在poller類ctor中創建輪詢線程 - 似乎沒有理由讓線程有更大的範圍。如果添加了更多設備,您只需創建更多輪詢實例即可。
在OnStart()中,創建一個輪詢實例(它自己創建輪詢線程)並返回,因此滿足'OnStart-Event不應該永久執行'的條件。
在OnStop()中停止線程?首先,嘗試停止線程的首選方法 - 不要嘗試去做。當服務管理器或任務管理器關閉時,您的服務是否正常運行並立即停止?如果是這樣,不要使不必要的,並可能適得其反的工作,試圖明確停止在OnStop()或輪詢類dtor中的輪詢線程。只需將OnStop()留空並查看它是否正常工作。
如果你發現你必須在服務進程被操作系統殺死之前終止一個線程,你可能不得不採取狡猾的手段來說服輪詢線程立即退出,否則你可能會逃脫Thread.Interrupt ()。取決於..
剛看到,我嘗試這樣做:
class poller
{
public static void ThreadProc()
{
for (;;)
{
Thread.Sleep(0);
}
}
Thread myThread;
public poller(){
myThread = new Thread(new ThreadStart(ThreadProc));
myThread.Priority = ThreadPriority.BelowNormal;
myThread.Start();
}
};
class WindowsService : ServiceBase
{
poller thisPoller;
public WindowsService()
{
this.ServiceName = "My Windows Service";
this.EventLog.Log = "Application";
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
thisPoller = new poller();
}
protected override void OnStop()
{
base.OnStop();
}
它內置並與一些項目屬性擺弄和運行installUtil的正確版本後安裝成功。它開始OK,睡眠(0)循環顯然是工作的,因爲服務出現在'進程'選項卡上,在我的i7上CPU使用約17%。當我在任務管理器服務中選擇「停止服務」時,服務狀態直接進入「停止」狀態,但進程消失約20秒(?)。
爲了更好玩,我真的裝上了箱子。我停止了服務,卸載與重建:
protected override void OnStart(string[] args)
{
base.OnStart(args);
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
thisPoller = new poller();
}
當我重新安裝和重新啓動,我知道這是工作,因爲我能聽到CPU風扇加快轉速之前,我可以得到任務管理器。果然,所有8個核心都100%。
即使使用8個CPU循環線程,停止也沒有問題。再次,狀態立即進入「停止」狀態,過程在20秒後消失。
將睡眠時間間隔設置爲'1000000',以便線程不運行也沒有任何問題 - 開始確定,停止確定。
你需要自己去一個,然後在遇到它們時回到特定的問題。 – Nick 2012-04-25 08:20:58