SetServiceStatus总是给出"无效的当前状态0"

时间:2016-08-17 14:42:00

标签: .net windows service version-control

我在Windows Server 2012上运行的服务是用VB.NET编写的,目标是.NET 4.5.2

每当我调用SetServiceStatus时,我得到"服务已报告无效的当前状态0"。没有给我带来大问题,服务继续运行正常,但我认为SCM可以关闭服务,如果它没有报告正确运行。

当我启动服务时,我在日志中遇到2个错误,我假设为PENDING和RUNNING调用:

Public Enum ServiceState As UInteger
    SERVICE_STOPPED = 1
    SERVICE_START_PENDING = 2
    SERVICE_STOP_PENDING = 3
    SERVICE_RUNNING = 4
    SERVICE_CONTINUE_PENDING = 5
    SERVICE_PAUSE_PENDING = 6
    SERVICE_PAUSED = 7
End Enum

<StructLayout(LayoutKind.Sequential)>
Public Structure ServiceStatus
    Public dwServiceType As Long
    Public dwCurrentState As UInteger
    Public dwControlsAccepted As Long
    Public dwWin32ExitCode As Long
    Public dwServiceSpecificExitCode As Long
    Public dwCheckPoint As Long
    Public dwWaitHint As Long
End Structure

Public Class myService
    Inherits System.ServiceProcess.ServiceBase

    Declare Auto Function SetServiceStatus Lib "advapi32.dll" (ByVal handle As IntPtr, ByRef serviceStatus As ServiceStatus) As Boolean

    Private _serviceStatus As ServiceStatus

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

        _serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING
        SetServiceStatus(Me.ServiceHandle, _serviceStatus)


        _serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING
        SetServiceStatus(Me.ServiceHandle, _serviceStatus)

    End Sub

   Protected Overrides Sub OnStop()

        _serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED
        SetServiceStatus(Me.ServiceHandle, _serviceStatus)

    End Sub

End Class

1 个答案:

答案 0 :(得分:1)

如果您使用来自https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx的VB.Net的默认手册,您会发现它们是从较旧的VB6版本转换而来的,其类型为LONG(32Bit int),但现在应该调用它Integer(32位int)。

尝试以下结构

  <StructLayout(LayoutKind.Sequential)>
Public Structure ServiceStatus
    Public dwServiceType As Integer
    Public dwCurrentState As ServiceStateEnum
    Public dwControlsAccepted As Integer
    Public dwWin32ExitCode As Integer
    Public dwServiceSpecificExitCode As Integer
    Public dwCheckPoint As Integer
    Public dwWaitHint As Integer
End Structure