C#服务程序监听端口问题
倒退一天 2010-05-21 06:15:57 具体描述:C#服务程序中,启动监听端口功能,挂起接收客户端连接,有连接就发出HELLO字符串。待启动服务后,再关闭,则此服务进程延时10多秒后才结束。经过多方面测试,始终无法关闭主线程的时候就结束掉子线程。(前提是不允许强制关闭进程),用什么办法才能是服务停止,进程马上就关闭。或者这段代码要怎么改。
代码如下:
Thread threadsockt = null;
protected override void OnStart(string[] args)
{
threadsockt = new Thread(new ThreadStart(PortBind));
threadsockt.Start();
}
private void PortBind()
{
int port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PortTcp"].ToString());
IPAddress serverIP = IPAddress.Any;
IPEndPoint server = new IPEndPoint(serverIP, port);
TcpListener listener = new TcpListener(server);
listener.Start();
while (true)
{
try
{
TcpClient client = listener.AcceptTcpClient();
Socket clientsocket = client.Client;
Thread threadback = new Thread(new ParameterizedThreadStart(this.mainServerProcess));
threadback.IsBackground = true;
threadback.Start(clientsocket);
}
catch (Exception e)
{
writeError.WriteLog("PortBind", e.Message);
}
}
}
private void mainServerProcess(object socket)
{
Socket clientsockt = socket as Socket;
byte[] buffer = new byte[5];
string sendStr = "HELLO";
buffer = System.Text.Encoding.Default.GetBytes(sendStr);
clientsockt.Send(buffer);
clientsockt.Close();
}
protected override void OnStop()
{
我要在此处写什么代码才能在停止服务的时候,马上就能结束进程。(不要跟我说强制关闭)
但是问题在没有客户端连接的时候,挂起的监听怎么会产生子线程呢?但测试事实就是因为子线程没结束而延迟了进程的关闭。哪位高手指教一二。
//System.Environment.Exit(0);
//threadsockt.Abort();
}