失败,我有下面的代码,在调试或作为一个独立的Windows应用程序执行正确的实例:TcpListener.AcceptSocket()在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服务?
这很可能是'开始',这是抛出'SocketException'。由于它不在你的尝试中,你的捕捉并最终不会被击中。将你的'Start'移动到你的try中,并在catch语句中检查'SocketException'的ErrorCode属性。这会让你更好地认识到错在哪里。然后检查ErrorCode对[此列表](http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v = vs.85).aspx)查看确切的问题是什么。 – vcsjones
让自己熟悉如何调试服务。这是可能的。 – usr
@vcsjones我试着用相同的结果。我还在'tcpListener.AcceptSocket()'之前和之后添加了日志记录,它在调用之前成功记录,但不成功之后。 –