2

我有一个用 Threads 制作的聊天服务器,运行良好,我连接了 5 个客户端,但 CPU 使用率及时增加到 100%!probe放了一个Thread.Sleep(30000),但是没有解决问题,这里是连接新客户时的代码

public void StartListening()
    {

            // Get the IP of the first network device, however this can prove unreliable on certain configurations
            IPAddress ipaLocal = ipAddress;

            // Create the TCP listener object using the IP of the server and the specified port
            tlsClient = new TcpListener(ipaLocal, 1986);

            // Start the TCP listener and listen for connections
            tlsClient.Start();

            // The while loop will check for true in this before checking for connections
            ServRunning = true;

            // Start the new tread that hosts the listener
            thrListener = new Thread(KeepListening);
            thrListener.Start();


    }

    private void KeepListening()
    {
        // While the server is running
        while (ServRunning == true)
        {
            // Accept a pending connection

            tcpClient = tlsClient.AcceptTcpClient();
            // Create a new instance of Connection
            Connection newConnection = new Connection(tcpClient);

            Thread.Sleep(30000);
        }
    }
}
4

2 回答 2

4

AcceptTcpClient是一个阻塞调用,所以没有理由调用Thread.Sleep

AcceptTcpClient 是一种阻塞方法,它返回可用于发送和接收数据的 TcpClient。

我认为您的 100% CPU 利用率问题可能在您的应用程序的其他地方。

于 2012-12-14T15:08:42.983 回答
2

使用名为 BeginAcceptTcpClient 的 AcceptTcpClient 异步版本。带有代码示例的 BeginAcceptTcpClient 文档可在此处获得。

于 2012-12-14T15:14:49.943 回答