1

I have developed a simple windows service using below code. When I start the service, it takes about 20 seconds, the service does not start and I get the error message I mentioned on title.

Note: It logs "Starting..." in event log but looks like the code after that does not run. Please advise.

Dim eventId As Integer = 0

Private Sub OnTimer(sender As Object, e As Timers.ElapsedEventArgs)
    EventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId)
    eventId = eventId + 1
End Sub

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

    EventLog.WriteEntry("Starting...") ' this line executes

    Dim timer As System.Timers.Timer = New System.Timers.Timer()
    timer.Interval = 60000 ' 60 seconds
    AddHandler timer.Elapsed, AddressOf Me.OnTimer
    timer.Start()
    Return

    ''''' some unused code below as I have Return
End Sub
FLICKER
  • 6,439
  • 4
  • 45
  • 75
  • Thank for response. I updated my code using Microsoft example. now it shows the same message immediately. – FLICKER Feb 09 '16 at 22:46
  • I'm not sure what the problem is. Your code looks ok now, and I've just pulled your code into a test application and it works fine for me locally. – adrianbanks Feb 09 '16 at 23:12
  • It looks good to me either. I'm still struggling with it. Thank you anyway. – FLICKER Feb 09 '16 at 23:17

2 Answers2

2

Windows gives a service up to around 30 seconds for the OnStart method to return. If it doesn't within this time, Windows assumes that the service hasn't started properly and gives you the error.

Your OnStart method never returns, as you have an infinite loop inside it. What you need to do is to create new thread in the OnStart method, start it, then return. The new thread should do any work you want the service to actually do.

adrianbanks
  • 81,306
  • 22
  • 176
  • 206
0

After research more on SO, I found the problem was I was using the Debug build!!! See the post

Community
  • 1
  • 1
FLICKER
  • 6,439
  • 4
  • 45
  • 75