Luk*_*uke 5 c# loops windows-services
请您帮我弄清楚为什么我的服务在事件日志中报告以下错误消息:
[服务名称] 服务报告了无效的当前状态 0。
这是我的主要功能:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
// Setup Ninject
var kernel = ConfigureNinject();
#if DEBUG
var service = kernel.Get<UpdateTakerStatus>();
service.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
kernel.Get<UpdateTakerStatus>()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
Run Code Online (Sandbox Code Playgroud)
...这是我的UpdateTakerStatus课程,我的逻辑在一个新线程中被调用:
public partial class UpdateTakerStatus : ServiceBase
{
private Thread WorkerThread;
private AutoResetEvent StopRequest = new AutoResetEvent(false);
private ServiceStatus serviceStatus = new ServiceStatus();
public ITakerStatusService TakerStatusService { get; set; }
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool SetServiceStatus(IntPtr handle, ref ServiceStatus serviceStatus);
public UpdateTakerStatus(ITakerStatusService takerStatusService)
{
InitializeComponent();
this.TakerStatusService = takerStatusService;
}
public void onDebug()
{
this.OnStart(null);
}
protected override void OnStart(string[] args)
{
// Update the service state to Start Pending.
serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
serviceStatus.dwWaitHint = 100000;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
this.WorkerThread = new Thread(UpdateTakers);
this.WorkerThread.Start();
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
private void UpdateTakers()
{
while (true)
{
#if (!DEBUG)
// Run this code until the service is stopped
if (StopRequest.WaitOne())
{
return;
}
#endif
this.TakerStatusService.CalculateFinalResultsForTakers();
}
}
protected override void OnStop()
{
serviceStatus.dwCurrentState = ServiceState.SERVICE_STOP_PENDING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
this.StopRequest.Set();
this.WorkerThread.Join();
serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
}
Run Code Online (Sandbox Code Playgroud)
当我在 Visual Studio 中调试它时,该服务完全正常,但是一旦我部署它,它似乎处理项目的速度非常慢并报告该错误消息。
然而,它似乎正在处理项目,表明代码设置正在执行一些有希望的事情。处理在我的服务方法调用this.TakerStatusService.CalculateFinalResultsForTakers();中执行。
我没有包含此代码,因为我担心此错误可能是服务通常设置不正确的症状 - 不是在线程中执行的代码?
我想知道我是不是设置错了?
解决方案在这里,我相信: Service Causes SCM Error "reported an invalid current state 0"。我遇到了完全相同的问题,并找到了此页面和我链接到的页面。在 ServiceStatus 结构的互操作声明中将“long”更改为“uint”。