多年來,編寫 Windows 服務一直被視為 C++ 程式設計師的專屬領域。隨著 .NET Framework 的推出,VB.NET 和 C# 也能輕鬆開發服務。但對於擁有豐富 VC++ 經驗的開發者,使用托管 C++ (Managed C++) 開發服務依然極具吸引力。本文將示範如何在 Visual Studio .NET 中建立、實作與部署托管 C++ Windows 服務。
CGNotifier),以便在服務列表中識別。System::ServiceProcess::ServiceBase 的類別,並開啟設計檢視,可拖放 Timer、資料庫連線等非視覺元件。切換至程式碼檢視,主要包含建構函式、Dispose 方法,以及兩個關鍵的虛擬方法覆寫:OnStart 與 OnStop。
OnStart:服務啟動邏輯OnStart 方法必須快速返回,否則服務管理員會認為啟動逾時。若需長時間運行的工作,必須另闢執行緒。典型模式如下:
private:
bool stopping;
int loopsleep; // 毫秒
Threading::Thread* servicethread;
protected:
void OnStart(String* args[])
{
Threading::ThreadStart* threadStart = new Threading::ThreadStart(this, &MyService::mainLoop);
servicethread = new Threading::Thread(threadStart);
servicethread->Start();
}
void mainLoop()
{
loopsleep = 1000; // 1 秒
stopping = false;
while (!stopping)
{
// 執行週期性任務
Threading::Thread::Sleep(loopsleep);
}
}
OnStop:優雅停止void OnStop()
{
stopping = true; // 設定旗標,讓主迴圈自然結束
}
注意:loopsleep 值過大會增加服務停止的回應延遲,需根據業務需求平衡。
建置專案後,產生的組件可透過 InstallUtil.exe 安裝為系統服務,或建立安裝專案 (Setup Project) 產生 MSI 安裝包,實現自動化部署。