有人可以帮我解决我的 Windows 服务项目中的这个错误吗?
我可以成功运行此服务,它工作完美,但任何时候服务停止时都会显示此错误:
C:\WINDOWS\system32>sc start EmailAutoResponseService
[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
调用 OnStop() 后会显示此错误。我假设它与我的 OnStart 方法和/或我使用 async/await 的方式有关。
有人可以指出我正确的方向吗?也请随意提出其他建议,这里不需要 async/await 吗?
这是我的 Program.cs 文件:
这是我的 EmailAutoResponseService.cs 文件:
相关方法如下:
/// <summary>
/// Initializes a new instance of the EmailAutoResponseService class.
/// </summary>
public EmailAutoResponseService()
{
InitializeComponent();
LoadDependencies();
_cts = new CancellationTokenSource();
}
protected override void OnStart(string[] args)
{
LogTs.LogInfo("Running OnStart().");
Task.Run(async () => await StartServiceAsync());
}
protected override void OnStop()
{
LogTs.LogInfo("Running OnStop().");
Task.Run(async () => await StopServiceAsync()).Wait();
}
public async Task StartServiceAsync()
{
LogTs.LogInfo("Running StartServiceAsync().");
await RunEmailProcessingLoop(_cts.Token);
}
/// <summary>
/// Stops the service asynchronously.
/// </summary>
public async Task StopServiceAsync()
{
LogTs.LogInfo("Running StopServiceAsync().");
_cts.Cancel();
// Give some time for the cancellation to be processed
await Task.Delay(1000);
}
OnStart 方法应在几秒钟内完成:
Task _mainloop;
protected override void OnStart(string[] args)
{
LogTs.LogInfo("Running OnStart().");
Task.Run(() => StartService());
}
void StartService()
{
LogTs.LogInfo("Running StartServiceAsync().");
_mainloop = RunEmailProcessingLoop(_cts.Token);
}
void StopService()
{
LogTs.LogInfo("Running StopServiceAsync().");
_cts.Cancel();
// Wait for the cancellation to be processed
_mainloop.Wait();
}
相应地编辑
RunEmailProcessingLoop
。