Skip to content

windows service in C#

April 22, 2013

First approach with Windows Service is not easy..

Lot of time ago, i have written a c# service.

This is the logic of the Service class (tested, works fine):

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);

        protected override void OnStop()
            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());

I recommend to write your real service work in a separate static method (why not, in a console application…just add reference to it), for simplify debugging and cleaning service code.

Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

Hope this help!




From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: