We help IT Professionals succeed at work.
Get Started
Troubleshooting Question

Windows Service with tcp client increase usage CPU

49 Views
Last Modified: 2020-11-28
Hello, Experts!
I write simple windows service, which receive tcp/ip message from other windows service and response it. Like monitoring service.  But I have some problem. If I turn off the service and then turn on, usage CPU increase..
Here is my code
Windows service srtart:
public partial class Monitoring : ServiceBase{
 protected override void OnStart(string[] args)
        {
            Thread monitor = new Thread(() =>
            {
                monitoringListener = new MonitoringListener();
                monitoringListener.Start();
            });
            monitor.Start();
        }

}

My monitor listener class:
sealed class MonitoringListener
{
 internal MonitoringListener() => listener = new TcpListener(iPAddress, port);

internal void Start()
{
   Log.Write("Start greenSquare service");            
   try
   {
      listener.Start();
      while (true)
      {
         if (listener.Pending())
         {
            Thread serverThread = new Thread(() =>
            {
               using (TcpClient client = listener.AcceptTcpClient())
               {
                  ClientObject clientObject = new ClientObject();
                  clientObject.Process(client);
               }                               
           });
           serverThread.Start();
         }
         Thread.Sleep(10);
      }
   }
   catch (Exception ex)
   {
      Log.Write(ex.ToString());
   }
}
}
My ClientObject class:
public class ClientObject
    {
   internal void Process(TcpClient tcpClient)
        {
            NetworkStream stream = null;
            byte[] data = new byte[Marshal.SizeOf(typeof(ExchangeBuffer))];
            int readingBytes, totalBytes, buffSize;
            try
            {
                stream = tcpClient.GetStream();                
                while (tcpClient.Connected)
                {
                    totalBytes = readingBytes = 0;                    
                    buffSize = data.Length;
                    do
                    {
                        readingBytes = stream.Read(data, totalBytes, buffSize);
                        totalBytes += readingBytes;
                        if (readingBytes <= 0 || totalBytes >= buffSize)
                            break;
                        buffSize -= readingBytes;
                    }
                    while (stream.DataAvailable || buffSize > 0);
                    if (totalBytes > 0)
                    {
                        // get message 
                        ExchangeBuffer message = Serializer.Deserialize<ExchangeBuffer>(data);
                        // process message
                        ExchangeBuffer response = Handlers.MessageHandlers[(ActField)message.nAct].Handle(message, tcpClient.Client);
                        // response....
                        data = Serializer.Serialize(response);
                        stream.Write(data, 0, data.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex.ToString());
            }
            finally
            {
                stream?.Close();
                tcpClient?.Close();
            }
        }
}
Comment
Watch Question
Developer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This problem has been solved!
Unlock 2 Answers and 4 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE