Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Methods in Windows Service not working as Timer events

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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') ;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading