Properly stopping a .net windows service

Posted on 2009-07-01
Last Modified: 2013-12-17
How can I stop a windows service from within the code and have the service show as stopped in the WMI?  For example, if I am looking for a config file on startup and don't find it, I just want to stop the service.  I tried the code below, and it does stop executing the code in the DoWork routine (because the event log doesn't get wriitten to anymore), but the service still shows as started in the WMI.
Public Class TestService

    Private _worker As New Worker()

    Protected Overrides Sub OnStart(ByVal args() As String)

        Dim wt As System.Threading.Thread

        Dim ts As System.Threading.ThreadStart

        ts = AddressOf _worker.DoWork

        wt = New System.Threading.Thread(ts)


    End Sub

    Protected Overrides Sub OnStop()


    End Sub

    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


                End If

            End If

        End Sub

        Public Sub DoWork()

            Dim TestCounter As Integer = 0    'we'll stop the the service after we loop through twice

            m_thMain = System.Threading.Thread.CurrentThread

            Dim i As Integer = m_rndGen.Next

            m_thMain.Name = "Thread" & i.ToString

            While Not m_booMustStop

                TestCounter += 1

                System.Diagnostics.EventLog.WriteEntry("EmptyService", "Start work: " & m_thMain.Name)


                System.Diagnostics.EventLog.WriteEntry("EmptyService", "Finish work: " & m_thMain.Name)

                If TestCounter > 1 Then StopWork()

            End While

        End Sub

    End Class

End Class

Open in new window

Question by:grantdaddy
  • 3
LVL 14

Accepted Solution

shahprabal earned 500 total points
ID: 24757811
You need to use the System.ServiceProcess.ServiceController class :

Author Comment

ID: 24763405
Thanks shahprabal.  I tried the code below and it is kind of working.  The service still shows as Started in the WMI (even if you refresh the list or exit WMI and come back in) but if you try to stop the service through the WMI, you get a windows message box saying they service could not be stopped due to an internal error.  It is like the service really is stopped but WMI does not know it.

Is the code below what you would typically use?
Dim Services() As ServiceController = ServiceController.GetServices

For Each service As ServiceController In Services

   If service.ServiceName = "Test" Then


      Exit For

   End If


Open in new window

LVL 14

Expert Comment

ID: 24763463
1) Check the value of service.CanStop
This should be true else the service is created such that it can't be stopped.
2) Add this line after service.Stop()
3) Then check the status property value:
LVL 14

Expert Comment

ID: 24763471

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now