调试Windows Service时Timer事件失效:服务启动后直接停止
Windows服务Debug模式启动即停止+Timer提示音失效问题修复
问题描述
我做了个每6秒播放提示音的Windows服务,Debug模式启动后直接就停了,没任何报错。单独调用SystemSounds.Beep.Play()能正常响,但跟Timer结合就没用。原代码如下:
Service1代码
public partial class Service1 : ServiceBase { static Timer myTimer; public Service1() { InitializeComponent(); } public void OnDebug() { OnStart( null ); } protected override void OnStart( string[] args ) { myTimer = new Timer(); myTimer.AutoReset = true; myTimer.Interval = 60000; myTimer.Enabled = true; myTimer.Start(); myTimer.Elapsed += new ElapsedEventHandler( OnTimedEvent ); } private static void OnTimedEvent( object sender, ElapsedEventArgs e ) { SystemSounds.Beep.Play(); } protected override void OnStop() { } }
Main方法代码
static void Main() { #if DEBUG Service1 testService = new Service1(); testService.OnDebug(); #else ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); #endif }
问题原因
- Debug模式进程直接退出:Main方法调用
OnDebug()后没有任何阻塞逻辑,Main执行完毕整个进程就终止了,服务自然停止。 - Timer事件订阅顺序错误:先启动Timer再绑定
Elapsed事件,Timer第一次触发时还没有对应的处理方法,后续即使绑定了也可能因为Timer内部逻辑失效。 - Interval设置错误:代码里设的是60000(1分钟),但需求是6秒,应该是6000。
修复后的代码
修改后的Service1代码
public partial class Service1 : ServiceBase { static Timer myTimer; public Service1() { InitializeComponent(); } public void OnDebug() { OnStart( null ); } protected override void OnStart( string[] args ) { myTimer = new Timer(); myTimer.AutoReset = true; myTimer.Interval = 6000; // 修正为6秒 // 先绑定事件再启动Timer myTimer.Elapsed += OnTimedEvent; myTimer.Enabled = true; myTimer.Start(); } private static void OnTimedEvent( object sender, ElapsedEventArgs e ) { SystemSounds.Beep.Play(); } protected override void OnStop() { // 停止Timer并释放资源 myTimer?.Stop(); myTimer?.Dispose(); } }
修改后的Main方法代码
static void Main() { #if DEBUG Service1 testService = new Service1(); testService.OnDebug(); // 添加控制台等待,让进程保持存活 Console.WriteLine("服务已启动,按任意键停止..."); Console.ReadKey(); testService.OnStop(); #else ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); #endif }
修复说明
- 调整了Timer事件绑定顺序,确保启动前就有处理方法监听事件
- 修正Interval值为6000,符合每6秒触发的需求
- Debug模式下添加
Console.ReadKey()阻塞进程,避免服务启动后立即退出,同时补充了停止服务的逻辑 - OnStop方法里增加了Timer的停止和释放,避免资源泄漏
内容的提问来源于stack exchange,提问作者HARINDA VITHANA
相关产品推荐
相关产品推荐

