View Single Post
 
Old 07-29-2004, 08:22 AM
Merrion's Avatar
Merrion Merrion is offline
Ultimate Contributor

* Guru *
 
Join Date: Sep 2001
Location: Dublin, Ireland
Posts: 1,828
Default [Tip] Writing a service? Handle OnStart and OnStop asynchronously

When you start or stop a service in Windows if the OnStart or OnStop handler doesn't return within 20 seconds the service is marked as not working.

To prevent this do your OnStart or OnStop processing asynchronously....

Code:
Imports System.ServiceProcess

Public Class FunkehMunkehService
    Inherits System.ServiceProcess.ServiceBase

#Region "Asynchronous execution delegates"
    Public Delegate Sub OnStartDelegate()
    Public Delegate Sub OnStopDelegate()
#End Region

#Region "ServiceProcess.ServiceBase overrides"

    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.
        Dim OnStartDelegateInst As OnStartDelegate = AddressOf OnStartAsynch
        OnStartDelegateInst.BeginInvoke(AddressOf OnStopCallback, OnStartDelegateInst)

    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        Dim OnStopDelegateInst As OnStopDelegate = AddressOf OnStopAsynch
        OnStopDelegateInst.BeginInvoke(AddressOf OnStopCallback, OnStopDelegateInst)

    End Sub

#End Region

#Region "Asynchronous start/stop handling"
    Private Sub OnStartAsynch()
         '\\ Do the real start code here
    End Sub

    Private Sub OnStopAsynch()
        '\\ Do the real stop code here
    End Sub

    Private Sub OnStartCallback(ByVal ar As IAsyncResult)
        ar.AsyncState.EndInvoke(ar)
    End Sub

    Private Sub OnStopCallback(ByVal ar As IAsyncResult)
        ar.AsyncState.EndInvoke(ar)
    End Sub

#End Region

End Class
Reply With Quote