2012-12-14 44 views
2

Cpu使用率100%使用線程製作的聊天服務器,效果很好,我有5個客戶端連接,但CPU使用率增加到100%及時!探頭放了Thread.Sleep(30000),但並沒有解決問題,這裏是連接新客戶使用線程C#

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

AcceptTcpClient是一個阻塞調用時的代碼,所以沒有理由罵Thread.Sleep

AcceptTcpClient是一種阻塞方法,它返回可用於發送和接收數據的TcpClient。

我認爲你的100%CPU利用率問題可能在你的應用程序的其他地方。

1

使用稱爲BeginAcceptTcpClient的異步版AcceptTcpClient。具有代碼示例的BeginAcceptTcpClient的文檔可用here