我已经构建了一个 Windows 服务来监控我们服务器上的一些设置,我已经开发了很多 WinForm 和 WPF 应用程序,但在 Windows 服务方面我绝对是新手,这就是为什么我求助于 msdn 并按照教程如何创建一个简单的服务。现在我可以很好地安装该服务并使其运行,但前提是我从微软教程中删除了一些零碎的内容。但我很好奇为什么当我按照教程进行操作时,我的服务在启动时会出现意外错误。
经过一些测试后,该服务似乎在 SetServiceStatus() 的 onstart 方法中崩溃
public partial class MyService: ServiceBase
{
private static ManualResetEvent pause = new ManualResetEvent(false);
[DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
public static extern bool SetServiceStatus(IntPtr hServiceStatus, SERVICE_STATUS lpServiceStatus);
private SERVICE_STATUS myServiceStatus;
private Thread workerThread = null;
public MyService()
{
InitializeComponent();
CanPauseAndContinue = true;
CanHandleSessionChangeEvent = true;
ServiceName = "MyService";
}
static void Main()
{
// Load the service into memory.
System.ServiceProcess.ServiceBase.Run(MyService());
}
protected override void OnStart(string[] args)
{
IntPtr handle = this.ServiceHandle;
myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
**SetServiceStatus(handle, myServiceStatus);**
// Start a separate thread that does the actual work.
if ((workerThread == null) || ((workerThread.ThreadState & (System.Threading.ThreadState.Unstarted | System.Threading.ThreadState.Stopped)) != 0))
{
workerThread = new Thread(new ThreadStart(ServiceWorkerMethod));
workerThread.Start();
}
myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
SetServiceStatus(handle, myServiceStatus);
}
}
现在,当我注释掉这些行时,我的服务似乎运行得很好SetServiceStatus()
。为什么会失败?这是一个权利问题还是我完全错过了这里的重点?