我已经构建了一个Windows服务来监视我们的服务器上的一些设置,我已经开发了不少WinForm和WPF应用程序,但对于Windows服务我是一个绝对的新手,这就是为什么我诉诸于msdn,并按照教程how to create a simple service。现在,我可以安装该服务,并使其运行,但只有当我从微软教程中删减了一些零碎......但我很好奇为什么,当我按照教程,我的服务在启动时得到一个意外的错误。Windows服务 - 在启动时崩溃
经过一些测试,似乎该服务似乎OnStart方法崩溃在SetServiceStatus()
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()
线。为什么这会失败?这是一个权利问题还是我完全忽略了这一点?
你有调用'SetServiceStatus'的一些具体原因吗?这不是严格要求,你可能只是摆脱这些电话。 – CodingGorilla 2013-02-27 17:55:34
你可以按照这个简单的教程来做一个简单的Windows服务。所有这些外部电话都不需要您的服务工作。 [http://www.codeproject.com/Articles/14353/Creating-a-Basic-Windows-Service-in-C] – 2013-02-27 19:12:15
那么我没有具体的原因,只是试图跟随msdn,并想知道为什么在地球上它失败了。 – XikiryoX 2013-02-27 22:05:30