2

私は Threads で作成したチャット サーバーを持っていますが、うまく動作し、5 つのクライアントが接続されていますが、CPU 使用率が時間とともに 100% に増加します! プローブは 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 に答える