I'm creating this simple windows service to play a beep every six seconds. When I Start it on Debug Mode, it simply stops right after the start. There seem to be no errors or exceptions.
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()
{
}
}
My main method
static void Main()
{
#if DEBUG
Service1 testService = new Service1();
testService.OnDebug();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
The beep works fine on itself. But it doesn't work with timer.
CodePudding user response:
You need to keep on running your service, you can add this code after line testService.OnDebug();
. It will make your service run until you press q.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;