我们有一个案例,在服务启动(OnStart)期间,启动了一个工作线程。工作线程连接到 SQL 数据库。如果数据库不可用,工作线程可以向主线程发出故障信号。问题是; 如何向服务控制管理器发出启动失败的信号。
RegexCoder
问问题
2316 次
2 回答
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);
于 2009-03-20T18:04:23.960 回答
0
One way to stop it is to use the ServiceController, but you wont get any fancy message in the service control manager about an error or a failure to start.
var controller = new System.ServiceProcess.ServiceController("NameOfYourService");
controller.Stop();
于 2009-03-20T18:30:07.860 回答