【问题标题】:Cpu usage 100% with a chat server made with Threads C#使用 Threads C# 制作的聊天服务器的 Cpu 使用率 100%
【发布时间】:2012-12-14 15:02:17
【问题描述】:

我有一个用 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);
        }
    }
}

【问题讨论】:

    标签: c# multithreading chat cpu


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      使用AcceptTcpClient 的异步版本,称为BeginAcceptTcpClient。带有代码示例的 BeginAcceptTcpClient 文档可在 here 获得。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 2023-02-11
        • 1970-01-01
        • 2018-05-24
        • 2016-10-13
        • 1970-01-01
        相关资源
        最近更新 更多