Website Links

Tuesday 9 May 2017

C# - Polling Service

The Code

Polling services can be incredibly useful for picking up when something has changed and performing some actions. This post will cover how to set one up in C#. Firstly, you will want to create a new project with type Windows Service in Visual Studio:


You will then want to rename Service1.cs and all its references to be something more representative of your polling service. You will also want to update the name the polling service will appear with by clicking on Service1.cs to open the designer, and then right click within the designer and choose "Properties", then update ServiceName in the Properties view.


In order to view the code backing the polling service you can click on "click here to switch to code view" from within the designer. This code should look something like this:

    using System.ServiceProcess;
    using System.Timers;

    public partial class Service1 : ServiceBase
    {
        private Timer _timer;

        public Service1()
        {
            InitializeComponent();

            // Instantiating timer with 1000ms 
            // Every 1000ms the handler specified against _timer.Elapsed
            /// will be called. 
            _timer = new Timer(1000);
            _timer.Elapsed += ProcessThings;
        }

        private void ProcessThings(object sender, ElapsedEventArgs e)
        {
            // What you want to poll for 
        }

        protected override void OnStart(string[] args)
        {
            _timer.Start();
        }

        protected override void OnStop()
        {
            _timer.Stop();
        }
    }
 

You can put whatever you want in ProcessThings but personally, I add a console application project to the solution that handles all of the processing. This way I can debug it at will without the need to install the polling service/wait for the polling period.

Installation

Click on Service1.cs, then right click and choose "Add Installer", you can name serviceProcessInstaller1 and serviceInstaller1 whatever you like. Click on serviceProcessInstaller1 and select what account you would like the polling service to run with, I chose Local System which is quite common, and means that it is using the local user's account. After this you can build your project. To install it open the Developer Command Prompt for VS 2017 as an administrator and then navigate to where the .exe of your project is.

You can install using the following command:
installutil /i WindowsService1.exe

Alternatively, you can uninstall using the following command:
installutil /u WindowsService1.exe

No comments:

Post a Comment