Windows服务处于启动状态并且无法使其处于运行状态 [英] Windows service in starting state and can not make it in running state

查看:106
本文介绍了Windows服务处于启动状态并且无法使其处于运行状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中开发了一个Windows服务。我按照谷歌的一些现有教程。在service.cs类中,构造函数只持有InitializeComponent()方法。在OnStart()方法中,我编写了一些代码来打开一个端口,使用TCPClient通过tcp连接连接到其他客户端。在该OnStart()方法中,我使用AcceptTcpClient()方法从客户端接收响应,并转发到另一个类来处理客户端的响应并将其发送回客户端。我在ServiceInstaller和ServiceProcessInstaller中维护了编码方式,并启动服务,自动添加名为AfterInstall和Commited的事件处理程序。在我安装服务时,在service.msc中,它显示服务状态为启动,但服务正在按预期工作。为什么状态不显示运行状态?



我尝试过:



I developed a windows service in C#. I followed some existing tutorials from google. In service.cs class the constructor is only holding the InitializeComponent() method. In OnStart() method I have written some code to open a port using TCPClient to connect via tcp connection to some other client. In that OnStart() method I am receiving a response from client using AcceptTcpClient() method and forwarding to an another class to process the client's response and send it back to the client. I maintained the coding fashion in ServiceInstaller and ServiceProcessInstaller and to start the service automatically adding up the event handler named AfterInstall and Commited. As I am installing the service, in service.msc it is showing service status as starting but the service is working as it should. Why the status is not showing running state?

What I have tried:

public partial class WinService: ServiceBase
{
      private static TCPListen listener = null;

      public Winservice()
      {
            InitializeComponent();
      }
      
      protected override void OnStart(String[] args)
      {
            loadconfig(); // Loading configuration data variables like port number IPAddress
            listener = new TcpListener(IPAddress, PortNumber);
            listener.Start();
            AnotherClass handler = new AnotherClass(listener.AcceptTcpClient);
            Thread thd = new Thread(new ThreadStart(handler.HandleSession()));
            thd.Start();
      }

      protected override void OnStop()
      {
            listener.Stop();
      }

      public loadconfig()
      { Method implementation }
}

推荐答案

TcpListener.AcceptTcpClient()是一个阻止调用。因此,您的 OnStart()方法仅在客户端连接时返回。但是服务的启动例程应该尽快返回。如果它运行的时间太长,服务控制管理器将放弃等待函数返回让状态保持不变。



解决方案是执行Accept在自己的线程中调用。
TcpListener.AcceptTcpClient() is a blocking call. As a result, your OnStart() method will only return when a client has connected. But the start routine of a service should return as soon possible. If it runs for a too long time, the service control manager will give up waiting for the function to return letting the status unchanged.

The solution is to execute the Accept call within an own thread.


这篇关于Windows服务处于启动状态并且无法使其处于运行状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆