Windows Service的第一种方法并不容易。
很久以前,我写了一个C#服务。
这是Service类的逻辑(经过测试,可以正常工作):
namespace MyServiceApp{ public class MyService : Servicebase { private System.Timers.Timer timer; protected override void onStart(string[] args) { this.timer = new System.Timers.Timer(30000D); // 30000 milliseconds = 30 seconds this.timer.AutoReset = true; this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed); this.timer.Start(); } protected override void onStop() { this.timer.Stop(); this.timer = null; } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { MyServiceApp.ServiceWork.Main(); // my separate static method for do work } public MyService() { this.ServiceName = "MyService"; } // service entry point static void Main() { System.ServiceProcess.Servicebase.Run(new MyService()); } }}我建议您使用单独的静态方法(而不是在控制台应用程序中…直接添加对它的引用)编写您的实际服务工作,以简化调试和清理服务代码。
确保间隔足够,并仅在OnStart和OnStop替代中写入日志。
希望这可以帮助!



