gpt4 book ai didi

c# - TcpListener.AcceptSocket()在Windows服务中失败

转载 作者:行者123 更新时间:2023-12-03 12:05:13 26 4
gpt4 key购买 nike

我有以下代码的实例,可以在Debug中或作为独立的Windows应用程序正确执行:

TcpListener tcpListener = new TcpListener(IPAddress.Any, 4554);
tcpListener.Start();

while (true)
{
try
{
using (Socket socket = tcpListener.AcceptSocket())
{
// Code here is reached in Debug or as a Console Application
// but not as a Windows Service
}
}
catch (SocketException se)
{
// This is never reached
}
catch (Exception ex)
{
// This is never reached
}
finally
{
// This is never reached in the Windows Service
}
}

但是,当我将其安装为Windows服务时,它在 tcpListener.AcceptSocket()上崩溃,并将以下内容记录到事件查看器中:

An unhandled exception ('System.Net.Sockets.SocketException') occurred in MyService.exe [768]. Just-In-Time debugging this exception failed with the following error: The operation attempted is not supported.



即使试图捕获异常,我也无法再记录任何内容。在Debug中单步执行代码不会完成任何操作,因为代码成功阻止了应用程序并等待客户端连接。

有没有一种方法可以为Windows服务实现呢?

最佳答案

usr的建议(和this answer)使我发现了代码中的一个错误。 ServiceBase类包含以下内容:

protected override void OnStart(string[] args)
{
_worker = new Thread(ExecuteService);
_worker.Start();
}

private void ExecuteService()
{
for (;;)
{
if (_stop.WaitOne(1000))
{
new TcpServer().StartTcpServer();
return;
}
}
}

正确的实现是删除 for循环,该循环重新实例化了监听器。这是最终代码:
protected override void OnStart(string[] args)
{
_worker = new Thread(ExecuteService);
_worker.Start();
}

private static void ExecuteService()
{
new TcpServer().StartTcpServer();
}

关于c# - TcpListener.AcceptSocket()在Windows服务中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24896005/

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