2012-12-14 4 views
2

스레드 서버로 만든 채팅 서버가 있는데 제대로 작동하고 5 명의 클라이언트가 연결되어 있지만 CPU 사용이 100 % 증가합니다! 프로브는 Thread.sleep를 (30000)을 넣어,하지만 문제가 해결되지 않는, 여기스레드 서버 Cpu 사용률 100 % 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입니다.