Click here to Skip to main content
13,194,103 members (47,048 online)
Click here to Skip to main content
Add your own
alternative version


121 bookmarked
Posted 2 Dec 2006

How to Create a Simple Polling Service

, 15 Jan 2007
Rate this:
Please Sign up or sign in to vote.
An article to quickly and easily setup a polling service, i.e., a task that runs by itself in the background and periodically does something.


This article describes step-by-step, with screen snapshots, how to create a polling service using VB.NET and Visual Studio 2005. It solves the problem of using timers in a service, in a quick and simple manner.


Over the years, I have leaned on CodeProject to help me get started on many projects that involved programming technologies I was not familiar with at the time. This last project required me to create a service for a set of code I had already written. So, I headed over to CodeProject to figure out if my friends at CodeProject had a good article to do that. I was not disappointed. Mahmoud Nasr had written a highly rated and popular article, Simple Windows Service Sample.

Everything went fine until I needed to add the timer part. There are a great many opinions about which timers to use in a service. And, a Google search will yield many requests and complaints about all of them. I never did find a satisfactory article that explained how to do this seemingly simple thing. In addition, there were issues with multithreading and reentrancy when the timer fires before your task is ready to start over again.

I think I have solved this with a simple and quick solution. So, if you want to run a task repeatedly in the background, without worrying about reentrancy or multiple threading, and if you just want to wrap your code in a Windows Service, here is a very simple and straightforward way to do it.

Using the Code

The code I present, basically, follows the same steps to create a service that MSDN recommends. And, it is very similar to Mahmoud's article. The main difference being that it includes code to do polling, and shows you where you can drop your code in.

Executing the demo will install a service called "Polling Service". It will write an event log entry to the Application Log on your computer, every 30 seconds. The source code is everything you need to build the demo. It is also the final result of following the steps in this article.

1. Create New Service Project

Start by creating a new Visual Studio Project. Startup Visual Studio 2005.

Select the "Windows Service" template, and name the project.

Drag and drop the "Event Log" component from the toolbox onto your new service designer window.

Set the "ServiceName" and "(Name)" property to the name of your new service.

Set the "Log" property to "Application". Set the "Source" property to the name of your new service.

Enter the wrapper code for your service.

You can cut and paste the following code into the code window for your service. Change variable names and message text as appropriate for your service.

Imports System.Threading

Public Class PollingService
    ' Keep track of worker thread.

    Private m_oPollingThread As New Thread( _
        New System.Threading.ThreadStart(AddressOf PollProcess))

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things

        ' in motion so your service can do its work.

        EventLog1.WriteEntry("PollingService is starting.")

        ' Start the thread.

    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.

        EventLog1.WriteEntry("PollingService is stopping.")

        ' Stop the thread.

    End Sub

    Private Sub PollProcess()
        ' Loops, until killed by OnStop.

        EventLog1.WriteEntry("PollingService service polling thread started.")
            ' Wait...

            System.Threading.Thread.Sleep(30000) ' 30000 = 30 seconds

    End Sub

    Private Sub PollingPass()
            ' Do Stuff Here...

            EventLog1.WriteEntry("PollingService service polling pass executed.")
        Catch ex As System.Exception
            EventLog1.WriteEntry("PollingService encountered an error '" & _
                ex.Message & "'", EventLogEntryType.Error)
            EventLog1.WriteEntry("PollingService service Stack Trace: " & _
                ex.StackTrace, EventLogEntryType.Error)
        End Try
    End Sub

End Class

Notes About the Code

When the service is started, in the "OnStart" method, a new thread is started. You must start a new thread because the service manager controls this process. If you simply call the polling process from the OnStart method, the service manager would complain that the service does not respond. In other words, the OnStart method does not return control to the service manager.

That new thread loops indefinitely, and the only way to stop it is to issue the Abort command on the thread, which we do when we stop the service in the "OnStop" method.

The thread process continually executes two commands: the command to wait for a specified period of time, and then the command to run your code.

In my example, I have added exception checking to write any problems to the event log. The event log is the only way to debug a service during the startup time, as you can only interactively debug a service by attaching to the process "after" it has already started.

That's it for your service. Pretty simple, eh? Replace the comment "Do Stuff Here..." with the code you want to run on a periodic basis.

You can change the period that the service waits between executing your code, by changing the sleep time. It is specified in milliseconds, and there's 1000 milliseconds in a second.

2. Add Project Installer

The service is done. However, to run it, we can't just press the F5 button. We have to install the service. The following describes how to include in the project all the "stuff" needed to install the service on a computer.

Right click on the designer pane for your service, and select the option "Add Installer".

Everything is setup for you. You can choose how your service starts, by setting the "StartType" property. The default is "Manual". I've set it to "Automatic" in my example.

You can also specify which account the service runs under when it is started. Select the "ServiceProcessInstaller" component and set the "Account" property. The default is "User Account", and you will need to specify the username and password at installation time. I have set the example to use "LocalSystem" which does not require a username or password. Most Windows services run this way.

OK, now, when your application is run using the /install option, it will install itself as a service on your computer. And, when /uninstall is specified, it will remove the service from your computer.

Now, all we have to do is build the thing and resolve any build errors. To do that, select the properties of "My Project" in the Solution Explorer.

Change the "Startup Object" to the name of your service.

Now, build your solution.

3. Add Setup Project

OK, you have a service, let's add a setup procedure to this project to make it easy for others to install and use your funky new service.

Choose the "Setup Wizard" and choose a name. You can use the same name as your setup project.

Follow the setup wizard prompts.

Now, you need to add a custom action so that after all the files are copied over, the program is setup as a service.

We are done setting up the setup project. Now, build it.

4. Run It

Your service has been installed. Now, go to the Service Manager and start it. The Service Manager can be found in "Administrative Tools".

Start the service. Even though we set it to start automatically, it does not start automatically after we install the service. It will start automatically when the computer starts up.

Now, examine the event log to verify our service has started and is running successfully. The Event Viewer can be found in "Administrative Tools".

5. Notes on Uninstall

This example will continue to write event log messages to your application log every 30 seconds. Once you are convinced it works, you will want to uninstall it.

To do that, simply run the same .msi file that you ran to install it in the first place. It will prompt to Repair or Remove. Choose the Remove option.

Another way to remove your service is through the 'Add/Remove Software' Control Panel option. If you have lost or overwritten your .msi file with a new version, this is the only way to remove your service.

Before uninstalling a service: be sure to close the Services Viewer. If you do not and you have your service highlighted in the Service Viewer, the uninstall will not be able to remove your service. This is because the Service Viewer "locks" the service that is highlighted. The uninstaller will instead "mark" the service for deletion. When this happens, you cannot reinstall the service until the marked service is removed. There is no way to remove the marked service except by restarting the computer.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mark James Newman
Web Developer
Canada Canada
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionThis is a great article. Pin
Arpan Gutgutia26-Dec-12 10:17
memberArpan Gutgutia26-Dec-12 10:17 
GeneralMy vote of 5 Pin
abhi_here16-Oct-12 4:52
memberabhi_here16-Oct-12 4:52 
QuestionNice! Pin
Dramoth196411-Oct-12 5:00
memberDramoth196411-Oct-12 5:00 
Questionbest out there to start with Pin
kevinbarnett5506@yahoo.com21-Aug-12 5:25
memberkevinbarnett5506@yahoo.com21-Aug-12 5:25 
GeneralMy vote of 5 Pin
Nicholas Swandel6-May-11 5:18
memberNicholas Swandel6-May-11 5:18 
GeneralMy vote of 4 Pin
bill40736-Apr-11 22:20
memberbill40736-Apr-11 22:20 
GeneralMy vote of 5 Pin
mgnico17-Nov-10 3:42
membermgnico17-Nov-10 3:42 
GeneralSet Specific Poll Time Pin
jkbeaumont14-Aug-10 5:19
memberjkbeaumont14-Aug-10 5:19 
GeneralGreat article! Pin
Dezorian1-Mar-10 0:57
memberDezorian1-Mar-10 0:57 
GeneralService won't start (vs2008) Pin
corefour9-Nov-09 16:24
membercorefour9-Nov-09 16:24 
Creating this in vs2008 was easy, not much has changed. But the service does not start. I tried manually too and it reports 'the winsvc4sql service on Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service.' This is not expected, I think. There is an error log entry for each attempt:

Service cannot be started. System.ArgumentException: Source property was not set before writing to the event log.
at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at System.Diagnostics.EventLog.WriteEntry(String message)
at WindowsService4sql1.winsvc4sql.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

For more information, see Help and Support Center at

Anyone know what that's about? Maybe something is different about vs2008 here. Running on xp.
GeneralRe: Service won't start (vs2008) Pin
corefour9-Nov-09 16:35
membercorefour9-Nov-09 16:35 
GeneralPolling + network locations. Pin
Cgaens7-Nov-07 0:00
memberCgaens7-Nov-07 0:00 
GeneralRe: Polling + network locations. Pin
Mark James Newman7-Nov-07 2:58
memberMark James Newman7-Nov-07 2:58 
GeneralRe: Polling + network locations. Pin
Cgaens7-Nov-07 23:32
memberCgaens7-Nov-07 23:32 
GeneralThe service doesn't gracefully stops (I guess) Pin
Caio Proiete15-Oct-07 4:26
memberCaio Proiete15-Oct-07 4:26 
GeneralRe: The service doesn't gracefully stops (I guess) Pin
Mark James Newman15-Oct-07 7:20
memberMark James Newman15-Oct-07 7:20 
GeneralRe: The service doesn't gracefully stops (I guess) Pin
Caio Proiete15-Oct-07 22:46
memberCaio Proiete15-Oct-07 22:46 
GeneralRe: The service doesn't gracefully stops (I guess) Pin
Mark James Newman16-Oct-07 3:33
memberMark James Newman16-Oct-07 3:33 
GeneralExcellent!! Pin
Owen Freeman13-Oct-07 20:25
memberOwen Freeman13-Oct-07 20:25 
GeneralVery good article Pin
yahya.ammouri14-Aug-07 22:11
memberyahya.ammouri14-Aug-07 22:11 
GeneralRe: Very good article Pin
Mark James Newman15-Aug-07 2:55
memberMark James Newman15-Aug-07 2:55 
GeneralThe VERY Best!!!!!!!!!! Pin
betterc14-Jul-07 8:47
memberbetterc14-Jul-07 8:47 
GeneralRe: The VERY Best!!!!!!!!!! Pin
Mark James Newman15-Jul-07 2:50
memberMark James Newman15-Jul-07 2:50 
QuestionHow to Debug Pin
SumTinWong6-Jun-07 15:29
memberSumTinWong6-Jun-07 15:29 
AnswerRe: How to Debug Pin
Mark James Newman6-Jun-07 17:24
memberMark James Newman6-Jun-07 17:24 
GeneralRe: How to Debug Pin
SumTinWong7-Jun-07 6:31
memberSumTinWong7-Jun-07 6:31 
GeneralRe: How to Debug Pin
Mark James Newman7-Jun-07 6:57
memberMark James Newman7-Jun-07 6:57 
GeneralRe: How to Debug Pin
SumTinWong7-Jun-07 7:01
memberSumTinWong7-Jun-07 7:01 
GeneralRe: How to Debug Pin
adrianhcole1-Aug-07 7:03
memberadrianhcole1-Aug-07 7:03 
GeneralRe: How to Debug Pin
SumTinWong1-Aug-07 7:05
memberSumTinWong1-Aug-07 7:05 
QuestionInstall the windows service Pin
BMWABCD5-Jun-07 13:09
memberBMWABCD5-Jun-07 13:09 
AnswerRe: Install the windows service Pin
Mark James Newman6-Jun-07 17:27
memberMark James Newman6-Jun-07 17:27 
QuestionRe: Install the windows service Pin
BMWABCD8-Jun-07 5:13
memberBMWABCD8-Jun-07 5:13 
AnswerRe: Install the windows service Pin
Mark James Newman8-Jun-07 7:11
memberMark James Newman8-Jun-07 7:11 
GeneralGreat Article... Pin
Danny McGrath14-Mar-07 3:26
memberDanny McGrath14-Mar-07 3:26 
GeneralRe: Great Article... Pin
Mark James Newman14-Mar-07 4:42
memberMark James Newman14-Mar-07 4:42 
GeneralService Description Pin
Hugo de Vreugd27-Feb-07 23:22
memberHugo de Vreugd27-Feb-07 23:22 
GeneralStop the service Pin
Member #385558826-Feb-07 2:55
memberMember #385558826-Feb-07 2:55 
AnswerRe: Stop the service Pin
Mark James Newman26-Feb-07 5:20
memberMark James Newman26-Feb-07 5:20 
GeneralRe: Stop the service Pin
Brian Mohr26-Feb-07 5:23
memberBrian Mohr26-Feb-07 5:23 
GeneralRe: Stop the service Pin
Brian Mohr1-Mar-07 3:49
memberBrian Mohr1-Mar-07 3:49 
GeneralYou saved the day Pin
Kyle Flavell15-Feb-07 13:38
memberKyle Flavell15-Feb-07 13:38 
GeneralRe: You saved the day Pin
Mark James Newman15-Feb-07 14:18
memberMark James Newman15-Feb-07 14:18 
GeneralConvert C# Pin
rumiocean12-Jan-07 19:31
memberrumiocean12-Jan-07 19:31 
AnswerRe: Convert C# Pin
Mark James Newman13-Jan-07 10:30
memberMark James Newman13-Jan-07 10:30 
GeneralRe: Convert C# Pin
Fred Johanns24-Jan-07 2:36
memberFred Johanns24-Jan-07 2:36 
QuestionWhy not use a timer? Pin
Edwin Roetman12-Dec-06 11:27
memberEdwin Roetman12-Dec-06 11:27 
AnswerRe: Why not use a timer? Pin
Mark James Newman12-Dec-06 12:40
memberMark James Newman12-Dec-06 12:40 
GeneralRe: Why not use a timer? Pin
parkly12-Feb-07 12:25
memberparkly12-Feb-07 12:25 
GeneralRe: Why not use a timer? Pin
Mark James Newman12-Feb-07 20:18
memberMark James Newman12-Feb-07 20:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171018.2 | Last Updated 15 Jan 2007
Article Copyright 2006 by Mark James Newman
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid