设置服务状态始终提供"invalid current state 0"



我有一个运行在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

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

试试下面的结构

  <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

相关内容

最新更新