gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:29:39 25 4
gpt4 key购买 nike

我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com