VS C# tcp server/listener 获取错误 1053 服务在 运行 作为 Windows 服务时没有及时响应

VS C# tcp server/listener gets error 1053 the service did not respond in a timly fashion when ran as a Windows Service

我有一个用 Visual Studio 用 C# 编写的简单 TCP 服务器。一切正常,除非 运行 作为 Windows 服务,我在其中收到 1053 错误。我将其缩小到 TCP 侦听器部分,因为当我将它们注释掉时,服务就可以正常启动了。 这是我保存在 Service1.cs:

中的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;

namespace Vegas_Remote_Render_Server
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            var defaultwaittime = "20";
            int defaultport = 1302;
            


            TcpListener listener = new TcpListener(System.Net.IPAddress.Any, defaultport);
            listener.Start();
            while (true)
            {

                Console.WriteLine("Waiting for a connection.");

                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Client accepted.");
                NetworkStream stream = client.GetStream();
                StreamReader sr = new StreamReader(client.GetStream());
                StreamWriter sw = new StreamWriter(client.GetStream());

                try
                {
                    byte[] buffer = new byte[1024];
                    stream.Read(buffer, 0, buffer.Length);
                    int recv = 0;
                    foreach (byte b in buffer)
                    {
                        if (b != 0)
                        {
                            recv++;
                        }
                    }

                    string request = Encoding.UTF8.GetString(buffer, 0, recv);
                    string formattedrequest = Regex.Replace(request, @"^\s*$\n|\r", string.Empty, RegexOptions.Multiline).TrimEnd();

                    Console.WriteLine(request);
                    Console.WriteLine("request received");
                    sw.WriteLine("request received");
                    string[] splitrequest = request.Split('|');
                    var projectpath = "";
                    var parameternumber = 0;

                    var waittime = defaultwaittime;


                    foreach (string value in splitrequest)
                    {
                        parameternumber = parameternumber + 1;
                        if (parameternumber == 1)
                        {
                            projectpath = value;
                        }
                        if (parameternumber == 2)
                        {
                            waittime = value;
                        }


                    }



                    if (formattedrequest != "killrender")
                    {
                        Console.WriteLine(projectpath);
                        Console.WriteLine(waittime);
                        System.Diagnostics.Process.Start(@"render.bat", $"\"{projectpath}\" \"{waittime}\"");
                        sw.Flush();
                    }
                    if (formattedrequest == "killrender")
                    {

                        Console.WriteLine("killing instances");
                        System.Diagnostics.Process.Start(@"kill.bat");
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("Something went wrong.");
                    sw.WriteLine(e.ToString());

                }
            }
        }

        protected override void OnStop()
        {
        }
    }
}

为简化脚本,这里只提供TCP监听部分:

static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(System.Net.IPAddress.Any, defaultport);
        listener.Start();
        while (true)
        {
    TcpClient client = listener.AcceptTcpClient();
    NetworkStream stream = client.GetStream();
            StreamReader sr = new StreamReader(client.GetStream());
            StreamWriter sw = new StreamWriter(client.GetStream());
    }
}

我还在其他帖子中尝试了很多关于此服务问题的解决方案。这包括从 visual studio 导出 .exe 作为 Release 而不是 Debug,注释我在调试时使用的 console.WriteLine 命令,以及删除 while(true)。我的 Visual Studio 项目也使用项目模板“Windows Service C#”

我听说您可以通过修改注册表来为服务提供更多时间,但我不想使用该解决方案。 该服务在被视为“无响应”之前的工作时间。 我无法找到 TCP 侦听器的哪一部分正在执行此操作。

在此先感谢,我仍然是 C# 的新手

1053 个错误状态:

The service did not respond to the start or control request in a timely fashion.

此错误消息是发起服务启动请求后超时但未在window时间内响应的原因。

您的案例中的响应正在退出 OnStart() method. You use while(true) which is in many cases quite error prone. I suspect your service just enters the loop and ever exits because AcceptTcpClient is !blocking! operantion

AcceptTcpClient is a blocking method that returns a TcpClient that you can use to send and receive data. Use the Pending method to determine if connection requests are available in the incoming connection queue if you want to avoid blocking.

您需要将处理客户端的例程从 OnStart 方法中移出,以免阻塞它,只需将其移至单独的线程即可。

不要忘记在服务停止时Stop() TcpListener