代码:
private static TcpListener listener;
static System.Timers.Timer requestReceiver = new System.Timers.Timer(100);
在main中:
listener = new TcpListener(SERVER_IP, serverPort);
listener.Start();
requestReceiver.Elapsed += new ElapsedEventHandler(ReceiveRequest);
requestReceiver.Enabled = true;
现在我有听众的功能:
private static void ReceiveRequest(object source, ElapsedEventArgs e)
{
try
{
while (true)
{
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
int requestLength = stream.Read(requestBytes, 0, requestBytes.Length);
requestTable = (String[])ByteArrayToObject(requestBytes);
tcpClient.Close();
}
}
finally
{
listener.Stop();
}
}
这段代码创建了很多线程。可能这就是它在一段时间后崩溃的原因。我该怎么做才能避免创建线程?如何暂停监听过程?为什么这段代码创建了这么多线程?