简体   繁体   中英

Cpu usage 100% with a chat server made with Threads C#

I have a chat server made ​​with Threads, works well and I have 5 clients connected but CPU usage increases to 100% in time! probe put a Thread.Sleep (30000), but did not solve the problem, here is the code when connecting a new customer

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);
        }
    }
}

AcceptTcpClient is a blocking call, so there is no reason to call Thread.Sleep :

AcceptTcpClient is a blocking method that returns a TcpClient that you can use to send and receive data.

I think your 100% CPU utilization problem may be elsewhere in your application.

Use the async version of AcceptTcpClient called BeginAcceptTcpClient. The docs for BeginAcceptTcpClient with a code sample is available here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM