Windows服务无法启动

3
我正在遵循这个教程,使用Microsoft Visual Studio 2010创建和安装Windows服务:http://msdn.microsoft.com/en-us/library/zt39148a%28v=vs.100%29.aspx 我使用的是3.5 .NET Framework。经过多次尝试后,我从头开始创建了一个新的服务,但这一次没有为OnStart()方法提供方法体。该服务成功安装,但当我尝试使用服务管理器运行它时,它没有任何反应,过一会儿Windows告诉我该服务无法运行。
非常感谢您提供任何帮助。

1
如果 OnStart 方法什么也不做,服务将立即退出。通常,服务会启动一些前台线程来保持运行。 - Matt Davis
2个回答

1

OnStart()方法在服务启动时被系统调用。该方法应尽快返回,因为系统将等待成功返回以指示服务正在运行。在此方法中,通常会启动执行服务任务的代码。这可能包括启动线程、启动定时器、打开WCF服务主机、执行异步套接字命令等。

下面是一个简单的示例,它启动了一个线程,该线程只执行等待服务停止的循环。

private ManualResetEvent _shutdownEvent;
private Thread _thread;
protected override void OnStart(string[] args)
{
    // Uncomment this line to debug the service.
    //System.Diagnostics.Debugger.Launch();

    // Create the event used to end the thread loop.
    _shutdownEvent = new ManualResetEvent(false);

    // Create and start the thread.
    _thread = new Thread(ThreadFunc);
    _thread.Start();
}

protected override void OnStop()
{
    // Signal the thread to stop.
    _shutdownEvent.Set();

    // Wait for the thread to end.
    _thread.Join();
}

private void ThreadFunc()
{
    // Loop until the service is stopped.
    while (!_shutdownEvent.WaitOne(0))
    {
        // Put your service's execution logic here.  For now,
        // sleep for one second.
        Thread.Sleep(1000);
    }
}

如果您已经安装了服务,那么看起来您已经很接近成功了。值得一提的是,我有逐步说明如何从头开始创建服务的说明 在这里,以及关于如何让服务在命令行上自行安装/卸载而不依赖于InstallUtil.exe的后续说明 在这里

0

我终于成功解决了这个问题。显然,问题出在Visual Studio安装程序上,因为我设法编译了项目,然后在管理员模式下使用installutil安装了服务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接