c# - 为什么我的 Windows 服务会在大约 5 秒后自动退出?

标签 c# windows windows-services

我使用 C# 创建了一个 Windows 服务,当调用 OnStart 时,它会从另一个类创建一个新线程。这个新线程然后循环等待任何传入的 TCP 连接。或者它应该。当我启动服务时,它会在大约 5 秒后自动停止。我不知道为什么要这样做。我了解如果服务没有工作要做但已为其指定工作,则服务会自行关闭。任何人都知道为什么会发生这种情况?我的 OnStart 方法如下所示:

protected override void OnStart(string[] args)
    {
        Thread thread = new Thread(new StateMachine().AcceptConnections);
        thread.Start();      
    }

然后调用这个方法:

        Int32 port = 13000;
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");

        server = new TcpListener(localAddr, port);

        // Start listening for client requests.
        server.Start();
        // Enter the listening loop.
        do
        {
            client = server.AcceptTcpClient();
            ReceivedData();                
        } while (true);
    }

它不会停留足够长的时间以允许任何客户端连接到 TcpListner。

帮忙吗?

最佳答案

首先,确保您的应用代码在未设置为服务时运行正常。如果您的代码在未设置为服务时运行正常,我的猜测是您的 OnStart 由于某种原因花费的时间太长。如果您无法加快速度,此处的信息可让您处理必要的启动延迟。

在 Win32 中,您必须更新 service status通过定期通知服务控制管理器 (SCM) 启动(和停止)进度,否则它会认为您的服务已挂起并终止它。您可能只需要执行一次此操作,或者如果您的初始化需要很长时间,则可以在计时器上执行此操作。当您的启动(停止)逻辑正在进行时,您告诉 SCM 您处于状态 START_PENDING (STOP_PENDING),一旦完成,您告诉它您处于 STARTED (STOPPED) 状态。

在托管世界中,这个目标是通过调用 ServiceBase.RequestAdditionalTime 来实现的。 .对该主题有全面的概述 here .报价单:

This is where your managed service needs to pay attention to avoid the SCM flagging your service as unresponsive.

  • You don’t have to explicitly update the state; ServiceBase does this for you when your OnStart or OnStop method completes
  • You do have to call RequestAdditionalTime if you expect the OnX method to exceed the timeout.

关于c# - 为什么我的 Windows 服务会在大约 5 秒后自动退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3812905/

相关文章:

asp.net - 从 ASP.NET 页面启动/停止 Window 服务

c# - C# 中的 Windows 服务 - 崩溃/错误

c# - 使用 C# 的文件路径

c# - 如何从一个逗号分隔的列表中填充两个单独的数组?

c# - C# 实现中的二叉搜索树

c# - EF6 在单次调用中获取计数

windows - 在批处理文件中,如何遍历其中包含空格的字符串?

c# - 我可以使用 Xamarin 为 Windows 7 编写应用程序吗?

windows - 在 Windows 中,除了可移植性之外,我应该使用 CreateFile 还是 fopen?

c# - 论坛未读帖子实现