gpt4 book ai didi

c# - 使用 Threads C# 制作的聊天服务器的 CPU 使用率 100%

转载 作者:行者123 更新时间:2023-12-01 19:15:56 26 4
gpt4 key购买 nike

我有一个用线程制作的聊天服务器,运行良好,我有 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);
}
}
}

最佳答案

AcceptTcpClient是一个阻塞调用,因此没有理由调用Thread.Sleep:

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

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

关于c# - 使用 Threads C# 制作的聊天服务器的 CPU 使用率 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13881139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com