[英]C# windows services program
我能夠創建一個簡單的Windows服務應用程序。 只是框架。 但我仍然感到困惑。 我應該把我的代碼放在Windows服務實際上做些什么。 我有一個單獨的程序,我想在此處包含/調用/合並。 應該把程序放在哪里? 我應該從哪里開始?
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// Change the following line to match.
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyNewService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
}
您需要覆蓋OnStart方法(以及其他類似方法,如OnStop
, OnShutdown
等)。
執行此操作時,請確保OnStart
方法不會阻塞或執行時間很長。 這通常意味着在自己的線程中運行您的實際服務邏輯。
重寫OnStart()方法以調用業務邏輯。 如前所述,您可以創建另一個線程來獲得該功能,也可以使用帶有定時器的Eventhandler(再次使用線程)來調用busineess邏輯。 服務必須將控制權返回給操作系統,因此Onstart方法應該在服務運行時將控制權返回給窗口。
要控制,暫停,恢復,關閉電源,停止事件,您需要覆蓋這些方法並在那里編寫邏輯。
根據需要在MyNewService
上覆蓋以下方法:
protected virtual void OnContinue();
protected virtual void OnCustomCommand(int command);
protected virtual void OnPause();
protected virtual bool OnPowerEvent(PowerBroadcastStatus powerStatus);
protected virtual void OnSessionChange(SessionChangeDescription changeDescription);
protected virtual void OnShutdown();
protected virtual void OnStart(string[] args);
您對使用On____
方法發送的各種事件做出反應(它們是虛擬的,因此您可以覆蓋它們)。
特別是在最簡單的情況下:
protected override void OnStart(string[] args)
{
//Do stuff here
}
您必須覆蓋OnStart()
函數。 我建議將構建函數中當前具有的所有代碼移動到同一個函數中,因為建議將構造函數留空(這不僅僅是服務,但這是另一個故事)。 在開始時,您通常會旋轉一個或多個線程來完成您想要的工作。 請記住,OnStart()必須盡可能返回。 您可能還需要在OnStop()函數中實現一些邏輯,以便優雅地阻止工作線程。
如前所述,不要將您的代碼放在OnStart()中。 為什么? 因為如果您的OnStart()方法沒有快速返回,服務管理器會將您的服務標記為無響應,並將關閉您。
所以,我把我的代碼放在一個Start()方法中,所有OnStart()都調用Start()。 像這樣:
protected override void OnStart(string[] args)
{
Start();
}
public static void Start()
{
... do stuff
}
此外,請注意,啟動服務的代碼將根據您是處於編譯模式還是調試模式而有所不同。
System.ServiceProcess.ServiceBase[] ServicesToRun; // Change the following line to match. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyNewService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun);
我這樣做是為了確保它的行為正確,我不必記得來回更改代碼來運行或調試。
if(Debugger.IsAttached)
Service.Start();
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.