There is an SMTP server that hangs on the 25th port of the local machine. When he catches the connection. it processes the client in a separate thread.

But what happens is: when it is just running, it takes up 0.0% of the CPU, after catching the 1st connection - already 25% of the CPU, then 50, and so on to 100, and there the computer is already full.

I tried to put Thread.Sleep (100), but did not help.

The most interesting thing is that after the connection with the client is broken, the CPU load does not fall.

Question: how to make sure that the service does not eat the CPU and releases it? It seems to me that I need some objects = null, but it did not help.

The code itself:

protected override void OnStart(string[] args) { SmtpHelper s = new SmtpHelper(this); Thread listen = new Thread(new ThreadStart(s.Listen)); listen.Start(); } 

Then: (Listen method)

 public void Listen() { int iter = 0; try { l.Write("***************START*******************"); l.Write("SMTP server started " + DateTime.Now.ToString()); SMTP_Listener = new TcpListener(IPAddress.Any, port); SMTP_Listener.Start(); while (true) { /*Создадим сначала номер потока и файл логов для него*/ Socket clientSocket; clientSocket = SMTP_Listener.AcceptSocket(); m_ConnectedIp = ParseIP_from_EndPoint(clientSocket.RemoteEndPoint.ToString()); m_ConnectedHostName = GetHostName(m_ConnectedIp); _email.ip = m_ConnectedIp; _email.port = 25; //номер сессии(клиента) _sessionId = clientSocket.GetHashCode().ToString(); _email.sessionId = Convert.ToInt32(_sessionId); l.Write("New session: " + _sessionId); l.Write("Создан поток для обработки клиента " + _sessionId); //запускаем обработку клиента var processor = new ClientProcessor(clientSocket, m_ConnectedIp, m_ConnectedHostName, _email, MaxMessageSize, CommandIdleTimeOut); processor._sessionId = _sessionId; UserSessionController.AddSession(Convert.ToInt32(_sessionId)); Thread newClient = new Thread(processor.StartProcessing); newClient.Name = _sessionId; newClient.IsBackground = true; // ??? newClient.Start(); l.Write("*********************************************************"); } } catch (Exception ex) { l.Write("SMTP Listen Error: " + ex.ToString()); throw; } } 

StartProcessing method:

 /// <summary> /// Основной цикл работы сервера /// </summary> public void StartProcessing() { try { string namethread = _sessionId; l.Write(String.Format("Клиент {0}: _connectedIp = {1}, _connectedHostName = {2}", _sessionId, _connectedIp, _connectedHostName), namethread); if (_clientSocket.Connected) { l.Write(">>>Socket connected", namethread); } else { l.Write("<<<Socket NOT connected", namethread); } SendData("220 " + System.Net.Dns.GetHostName() + " Service ready\r\n"); l.Write("'220 " + System.Net.Dns.GetHostName() + " Service ready' были отправлены клиенту", namethread); //РАБОТА С ВХОДНЫМИ ДАННЫМИ while (true) { //если есть данные, то считаем их if (_clientSocket.Available > 0) { //чтение команды клиента string lastCmd = ReadLine(); if (lastCmd.Trim() == String.Empty) { l.Write("Empty commmand (lastCmd)]", namethread); } else { l.Write("lastCmd: " + lastCmd, namethread); } //парсим команду if (lastCmd.Trim() != String.Empty) ProceedCommand(lastCmd, namethread); } else { //dump: l.Write("[Socket isn't available now]"); } } } catch (Exception ex) { l.Write("SMTP StartProcessing Error: " + ex.ToString()); throw; } } 
  • 2
    Listen, and you could not describe the essence of the problem immediately in the title? Avoid all the utterances of questions. - andreycha

1 answer 1

 while (true) { //если есть данные, то считаем их if (_clientSocket.Available > 0) чаще всего false { ReadLine(); } } 

This is, in fact, an infinite loop that loads the processor, even if the data does not come. Inside ReadLine you most likely have Socket.Receive , which Socket.Receive blocks execution until the data Socket.Receive . So just remove this if.

  • Now I will try - Leonard Bertone
  • In ReadLine () for me: int countRecieved = _clientSocket.Receive (currByte, 1, SocketFlags.None); - Leonard Bertone
  • @LeonardBertone yes, _clientSocket.Receive will wait for the data to _clientSocket.Receive without loading the processor - PashaPash
  • Question resolved! Thanks, @PashaPash - Leonard Bertone