Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Windows Services for VB.NET Developers  »  Coding the body
 »  Home  »  Windows Development  »  Windows Services for VB.NET Developers  »  Coding the body
Windows Services for VB.NET Developers
by Scott Rutherford | Published  12/20/2005 | .NET Newbie Windows Development | Rating:
Coding the body

We are now ready to add programming to the service to make it do something.

    The Service Class (Code-behind)

    The Service class (e.g. EmptyService) will receive the Start and Stop commands for the service and must therefore implement OnStart() and OnStop(), which both override methods in the base ServiceProcess class. When you implement the more simple Service, with a Timer control, you would set the Enabled property of the Timer to True in OnStart() and set it to False in OnStop(). For our example, we will use these start/stop event handlers to create and destroy threads which will run the meat of our program.

    The next section of the article will discuss the contents of the Worker class. For now, we will create a private member of the Service class of type Worker. This is a singleton object that attaches to the main running program thread and performs work. In the OnStart() event handler, a new thread is created, with its start-point set to the Worker object’s main method (called “DoWork()”). Then the thread is started. In the OnStop() event handler, the worker object is torn down by first calling its StopWork() method and then freeing any extra objects used by the service.

    Windows Service processes are started by the SCM, and hence their working directory is that of the system, by default. An optional step here is to move the working directory of the service to its program directory. I always do this to simplify program configuration inputs, logging outputs, etc.

    You can also implement OnPause(), and OnContinue() here. Remember these will never get called if you do not set the CanPauseAndContinue property of the Service. These handlers have no arguments, and should look very similar to the OnStart()/OnStop(), except there should be no building or tearing down of objects.

    Custom commands are out of the scope of this article. However, the OnCustomCommand() event handler is available to extend your service to respond to custom events that you may have other programs execute via the SCM. Use this method to add other interactions to your service (http://msdn2.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand.aspx).

    [Visual Basic]
    Imports System.ServiceProcess
    Public Class EmptyService
        Inherits System.ServiceProcess.ServiceBase
        Private worker As New worker()
        Protected Overrides Sub OnStart(ByVal args() As String)
            System.IO.Directory.SetCurrentDirectory(GetMyDir)
            Dim wt As System.Threading.Thread
            Dim ts As System.Threading.ThreadStart
            ts = AddressOf worker.DoWork
            wt = New System.Threading.Thread(ts)
            wt.Start()
        End Sub
        Protected Overrides Sub OnStop()
            worker.StopWork()
        End Sub
        Function GetMyDir() As String
            Dim fi As System.IO.FileInfo
            Dim di As System.IO.DirectoryInfo
            Dim pc As System.Diagnostics.Process
            Try
                pc = System.Diagnostics.Process.GetCurrentProcess
                fi = New System.IO.FileInfo(pc.MainModule.FileName)
                di = fi.Directory
                GetMyDir = di.FullName
            Finally
                fi = Nothing
                di = Nothing
                pc = Nothing
            End Try
        End Function
    End Class
    

    The Worker Class

    The Worker class controls the thread in which all program processing will occur. It is called when a new thread is started by the Service class, and as mentioned previously, its entry point is the DoWork() method–this is where processing will begin. When DoWork() is called, it attaches to the current thread, gives it a name, and then starts a loop in which processing occurs. For this example, the only processing is to write an entry to the Windows Event Log, sleep, and then write another.

    [Visual Basic]
    Public Class Worker
        Private m_thMain As System.Threading.Thread
        Private m_booMustStop As Boolean = False
        Private m_rndGen As New Random(Now.Millisecond)
        Public Sub StopWork()
            m_booMustStop = True
            If Not m_thMain Is Nothing Then
                If Not m_thMain.Join(100) Then
                    m_thMain.Abort()
                End If
            End If
        End Sub
        Public Sub DoWork()
            m_thMain = System.Threading.Thread.CurrentThread
            Dim i As Integer = m_rndGen.Next
            m_thMain.Name = "Thread" & i.ToString
            While Not m_booMustStop
                System.Diagnostics.EventLog.WriteEntry("EmptyService", "Start work: " & m_thMain.Name)
                System.Threading.Thread.Sleep(10000)
                System.Diagnostics.EventLog.WriteEntry("EmptyService", "Finish work: " & m_thMain.Name)
            End While
        End Sub
    End Class
    

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 01/04/2006)
Rating
Great!
 
Comment #2  (Posted by Shihab on 01/25/2006)
Rating
Very useful
 
Comment #3  (Posted by an unknown user on 01/28/2006)
Rating
I have been looking for an intro on Windows services. Thanks!
 
Comment #4  (Posted by an unknown user on 03/06/2006)
Rating
good one
 
Comment #5  (Posted by an unknown user on 03/23/2006)
Rating
Nice work!
 
Comment #6  (Posted by an unknown user on 03/23/2006)
Rating
Nice work!
 
Comment #7  (Posted by an unknown user on 03/28/2006)
Rating
Quite interesting.
 
Comment #8  (Posted by an unknown user on 03/29/2006)
Rating
good
 
Comment #9  (Posted by an unknown user on 03/29/2006)
Rating
good
 
Comment #10  (Posted by an unknown user on 04/28/2006)
Rating
Great Intro
 
Comment #11  (Posted by an unknown user on 05/15/2006)
Rating
Really great work. Thanks

I wonder if a windows service can consume a web service too ?
 
Comment #12  (Posted by an unknown user on 05/29/2006)
Rating
Sure a Service can consume a web service like any other Windows app. You need to ensure your security context will work -- i.e. the account that the Windows Service runs as must have ability to make web request (authenticate if necessary to web server, on proxy, etc.).
 
Comment #13  (Posted by an unknown user on 06/07/2006)
Rating
Great explanation
 
Comment #14  (Posted by an unknown user on 06/07/2006)
Rating
excellent! exactly what I needed.
 
Comment #15  (Posted by an unknown user on 07/18/2006)
Rating
most informative article i've found so far - at least it explains what i'm trying to achieve. shame the example is in vb though, such an ugly language. wish i could find more c# centred stuff...
 
Comment #16  (Posted by an unknown user on 09/14/2006)
Rating
Excellent!
 
Comment #17  (Posted by an unknown user on 09/15/2006)
Rating
Nice work!
 
Comment #18  (Posted by an unknown user on 10/02/2006)
Rating
Hi,
Nice project !
You can also uninstall a service using c:\winnt\SC.exe delete service1
Sc is part of the W2k Resource kit.
http://www.petri.co.il/download_free_reskit_tools.htm

Andy

 
Comment #19  (Posted by an unknown user on 10/23/2006)
Rating
I reviewed a dozen articles on the subject of building a service in vb.net, and this is the only one that actually works! Thanks a bunch Scott.
 
Comment #20  (Posted by an unknown user on 11/16/2006)
Rating
It works in 10 minutes :-)) Thanks
 
Comment #21  (Posted by an unknown user on 11/27/2006)
Rating
Just excellent! Thank you Scott
 
Comment #22  (Posted by Larry on 11/28/2006)
Rating
Hi, I cannot install this service. I compiled the code form this article and receiving an error message durring installaion: Unknown error "-1". Please help.

Thanks,
Larry
 
Comment #23  (Posted by an unknown user on 01/04/2007)
Rating
Excelent and simple! Thanks a lot.
 
Comment #24  (Posted by an unknown user on 01/18/2007)
Rating
Simple and to the point. Thank you.
 
Comment #25  (Posted by Doug on 01/23/2007)
Rating
As I have the "standard" edition, I can't seem to get this to work. It compiles & installs, but won't start, *immediately* throwing the "failed to start in a timely fashion."
What type of project must one start with, what does the project's property page look like?
 
Comment #26  (Posted by an unknown user on 02/12/2007)
Rating
what a childice example have you given.
 
Comment #27  (Posted by an unknown user on 02/19/2007)
Rating
How about some hint of "How to consume a win service/service Method form an application??
 
Comment #28  (Posted by [The author] on 02/19/2007)
Rating
RE; Comment #27: The article does present the concept of "OnCustomCommand" on page three. However, from your language I expect you are talking about Web Services which are clearly distinguished from Windows Services on page one.
 
Comment #29  (Posted by an unknown user on 03/12/2007)
Rating
Very helpful. Thanks!
 
Comment #30  (Posted by an unknown user on 05/03/2007)
Rating
I was looking for that installutil thingy... Thanks for the great input!
 
Comment #31  (Posted by an unknown user on 06/05/2007)
Rating
WS with timer explaination are many, with threads its really rare. This one is a good one out of those rare explainations.
 
Comment #32  (Posted by an unknown user on 06/06/2007)
Rating
Really good but needed debug process for development environment too.
 
Comment #33  (Posted by David on 06/07/2007)
Rating
Excellent explanations along with working code. The only questions I have left are how to get an icon in the system tray for this service and how to display a popup menu on a right click of that icon.
 
Comment #34  (Posted by an unknown user on 06/30/2007)
Rating
Thanks
 
Comment #35  (Posted by an unknown user on 07/21/2007)
Rating
Excellent understood very well keep it up and give us nice articles such as this
 
Comment #36  (Posted by Aakash on 09/06/2007)
Rating
This is my first exposure to Windows Services and the content was delivered very nicely, good work Scott.

(Comment #15) I do not digest why people hate VB, is it becuase it does those great things in simple manner where as its tough to achieve the same in their so called very good language ??
 
Comment #37  (Posted by Wardell Dye on 09/07/2007)
Rating
This was an excellent introduction to Windows Services as I was just given an assignment to preform a task to use Windows Services, great job!!!!!

Thanks
 
Comment #38  (Posted by an unknown user on 10/10/2007)
Rating
Perhaps I am missing something, but when I try to compile the code, I'm getting the following error: 'Sub Main' was not found in 'WindowsService1.Service1'. Do I need to change the Startup Object?

 
Comment #39  (Posted by an unknown user on 10/17/2007)
Rating
Compiled OK. Installed OK. Service Started...BUT...nothing in the event viewer when I start the service...
 
Comment #40  (Posted by Bobby on 11/29/2007)
Rating
When I try to start the service, I get this error. Any idea as to what could be happening?

Service cannot be started. System.ArgumentException: Delegate to an instance method cannot have null 'this'.
at System.MulticastDelegate.ThrowNullThisInDelegateToInstance()
at WindowsService.Service.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback
 
Comment #41  (Posted by Bobby on 11/29/2007)
Rating
Sorry, my mistake with above error. Works perfectly now. Thanks a lot.
 
Comment #42  (Posted by an unknown user on 12/10/2007)
Rating
Followed instructions and re-checked. Service will not install, so something must have been left out

 
Comment #43  (Posted by an unknown user on 02/19/2008)
Rating
Great sample. Following your instructions it works at first execution. Thanks very much !!!
 
Comment #44  (Posted by an unknown user on 03/26/2008)
Rating
it worked as per my requirement..
 
Comment #45  (Posted by an unknown user on 05/20/2008)
Rating
Brilliant -- just what I needed.
 
Comment #46  (Posted by an unknown user on 05/23/2008)
Rating
Excellent Explanation, But i was not found that how to communicate with service prepared, from client machine
 
Comment #47  (Posted by an unknown user on 06/08/2008)
Rating
Useful, but a lot of information is missing like getting the installer to actually install the service. The example here will not work as it is written.
 
Comment #48  (Posted by an unknown user on 06/12/2008)
Rating
Fantastic look at a simple windows service.
 
Sponsored Links