首页 > 解决方案 > Windows 服务:服务无法启动。服务进程无法连接到服务控制器

问题描述

我搜索了敌人的解决方案,但无法得到它。这是windows服务的代码。

 protected override void OnStart(string[] args)
    {
        Debugger.Launch();
        try {
           AsynchronousSocketListener.StartListening();



            // Log an event to indicate successful start.

            EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);

        }
        catch(Exception ex)
        {
            // Log the exception.
            EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);


        }
    }

这是AsynchronousSocketListner 类

 static string constr = "Integrated Security=SSPI;Persist Security Info=False;Data Source=WIN-OTVR1M4I567;Initial Catalog=CresijCam";

    //string test = constr;

    // Thread signal.  
    public static  ManualResetEvent allDone = new ManualResetEvent(false);

    private  AsynchronousSocketListener()
    {

    }
    public static void StartListening()
    {
        // Establish the local endpoint for the socket.  
        // The DNS name of the computer  

        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1200);

        // Create a TCP/IP socket.  
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(200);

            while (true)
            {
                // Set the event to nonsignaled state.  
                 allDone.Reset();

                // Start an asynchronous socket to listen for connections.  

                listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener);

                // Wait until a connection is made before continuing.  
                 allDone.WaitOne();
            }

        }
        catch (Exception e)
        {
            string me = e.Message;

        }

    }

我每次都会收到不同的错误消息:

等待来自 TCPService 服务的事务响应时达到超时(30000 毫秒)。

无法启动服务。服务进程无法连接到服务控制器

我不知道我得到的错误来自哪里。我知道一件事,服务还没有运行。它在这个方法 startListening() 中。我使用 Debugger.launch() 进行了调试。但我没有到达特定的线路。我也认为这与某处的 TCP 有关,但不能确定。

控制台项目的相同代码处于工作状态。我不知道在这里放什么其他代码。但是,如果需要更多详细信息,请告诉我。

标签: c#windows-services

解决方案


这个简单的答案是你AsynchronousSocketListener不是异步或线程或任何类型的。本质上,您的服务Start正在超时,并且永远不会命中

EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);

因为它本质上是永远阻塞


这个错误说明了一切

等待来自 TCPService 服务的事务响应时达到超时(30000 毫秒)。


OnStart应该只开始工作。这通常意味着产生一个新线程来完成实际工作。总之,预计OnStart及时完成。

您将需要重构代码以AsynchronousSocketListener在新线程或任务中运行


推荐阅读