我们有一种情况,在服务启动(OnStart)期间,启动工作线程。工作线程连接到SQL数据库。如果数据库不可用,则工作线程可以向主线程发出故障信号。问题是;如何通知服务控制管理器启动失败。
答案 0 :(得分:3)
这就是我们处理这种情况的方式。此代码已添加到我们的主服务类中,然后在我们想要将启动返回为失败的位置,调用SetServiceFail(1065),然后从OnStart返回。在这种情况下,1065返回一个不存在的数据库状态。
我还要注意,在SetServiceFail中,我对serviceType进行了硬编码,因为在我们的例子中,我们所有的服务都是独立的,所以我保持简单。
private void SetServiceFail (int ErrorCode)
{
SERVICE_STATUS _ServiceStatus = new SERVICE_STATUS ();
_ServiceStatus.currentState = (int) State.SERVICE_STOPPED;
_ServiceStatus.serviceType = 16; //SERVICE_WIN32_OWN_PROCESS
_ServiceStatus.waitHint = 0;
_ServiceStatus.win32ExitCode = ErrorCode;
_ServiceStatus.serviceSpecificExitCode = 0;
_ServiceStatus.checkPoint = 0;
_ServiceStatus.controlsAccepted = 0 |
(this.CanStop ? (int) ControlsAccepted.ACCEPT_STOP : 0) |
(this.CanShutdown ? (int) ControlsAccepted.ACCEPT_SHUTDOWN : 0) |
(this.CanPauseAndContinue ? (int) ControlsAccepted.ACCEPT_PAUSE_CONTINUE : 0) |
(this.CanHandleSessionChangeEvent ? (int) ControlsAccepted.ACCEPT_SESSION_CHANGE : 0) |
(this.CanHandlePowerEvent ? (int) ControlsAccepted.ACCEPT_POWER_EVENT : 0);
SetServiceStatus (this.ServiceHandle, ref _ServiceStatus);
}
public enum State
{
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
}
public enum ControlsAccepted
{
ACCEPT_STOP = 1,
ACCEPT_PAUSE_CONTINUE = 2,
ACCEPT_SHUTDOWN = 4,
ACCEPT_POWER_EVENT = 64,
ACCEPT_SESSION_CHANGE = 128
}
[StructLayout (LayoutKind.Sequential)]
private struct SERVICE_STATUS
{
public int serviceType;
public int currentState;
public int controlsAccepted;
public int win32ExitCode;
public int serviceSpecificExitCode;
public int checkPoint;
public int waitHint;
}
[DllImport ("advapi32.dll")]
private static extern bool SetServiceStatus (IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
答案 1 :(得分:0)
阻止它的一种方法是使用ServiceController,但是你不会在服务控制管理器中得到关于错误或无法启动的任何奇特消息。
var controller = new System.ServiceProcess.ServiceController("NameOfYourService");
controller.Stop();