简体   繁体   中英

Where to put my code so that it executes after my service starts?

just wondering where to put my code so that it executes after my service starts.

currently i have my code like this

    namespace sendMailService
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }


            protected override void OnStart(string[] args)
            {
                this.sendMail();

            }
            protected override void OnStop()
            {
            }
            private void sendMail() 
            {
              // My actual service code
            }
        }

    }

When i start the service, it wouldn't get to "Running" mode till the this.sendMail() completes. Incidentally, the last line of the sendMail() function is to stop() the service. So, the service crashes by the time it executes the OnStart method.

I know why its happening like this (because the code is in OnStart ). The question is where to call the sendMail() so that the Service gets to running mode and then execute the function.

You can decorate your code as to fix your problem.

namespace sendMailService
{
    public partial class Service1 : ServiceBase
    {
        private System.Threading.Timer IntervalTimer;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            TimeSpan tsInterval = new TimeSpan(0, 0, Properties.Settings.Default.PollingFreqInSec);
            IntervalTimer = new System.Threading.Timer(
                new System.Threading.TimerCallback(IntervalTimer_Elapsed)
                , null, tsInterval, tsInterval);
        }

        protected override void OnStop()
        {
            IntervalTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            IntervalTimer.Dispose();
            IntervalTimer = null;
        }

        private void IntervalTimer_Elapsed(object state)
        {   
             // Do the thing that needs doing every few minutes...
             sendMail();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM