Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Tcp Server performance issues after implementing thread pool

I have read several discussion on the matter and managed to understand a bit, but still having some issues solving the performance problem when converting from Thread class to ThreadPool class

Details:

I have build a tcp server, with educational purpose(the task should not be with async methods), which is accepting client connections and create a new thread for each client. With this method the application is executed for less than a second, but when decided to move to a next level solution like thread pool my performance dropped to 40-50 seconds for just a hundred clients and i just send a 2048 byte buffer, receive it and close.

The first 12 threads are very fast, most probably because my cpu is 6 cores 12 threaded and after that the threads start to experience a delay. I am open to solution ideas and structure approach.

Server code:

public void OnSocketReceive()
    {
        while (!this.exitServer)
        {
            if (!tcpListener.Pending())
            {
                Thread.Sleep(10);
                continue;
            }

            TcpClient client = tcpListener.AcceptTcpClient();

            IManageConnectedUser chatLogic = new ManageConnectedUser(connections, welcomeMessage);

            //Thread clientThread = new Thread(new ParameterizedThreadStart(chatLogic.OnClientConnection));
            //clientThread.Start(client);

            ThreadPool.QueueUserWorkItem(chatLogic.OnClientConnection, client);
        }

More clarification

By far with the debugging I have done and the discussions I have read I made the conclusion that the problem is the blocking code in OnClientConnection function and more specifically in the inner function which is stringCreateHandler. Where i receive this error: System.Threading.ThreadInterruptedException: Thread was interrupted from a waiting state on line 39, which is the Thread.Sleep(10);

public string stringCreateHandler(TcpClient client)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            do
            {
                if (client.Available > 0)
                {
                    while (client.Available > 0)
                    {
                        char ch = (char)client.GetStream().ReadByte();

                        if (ch == '\r')
                        {
                            continue;
                        }
                        if (ch == '\n')
                        {
                            return sb.ToString();
                        }

                        sb.Append(ch);
                    }
                }

                Thread.Sleep(10);
              
            } while (true);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

    }

I have checked the rest of the code i don't think there is more blocking code, but i am giving a link to the project https://github.com/nikolaymih/Chat-Project/tree/master/ChatProjectNewThreads The only difference there is the Thread class instead of ThreadPool but this is just for orientation

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Looking at your full project, I think your issue is that OnClientConnection is long-running: it won't return until that connection is closed, and since this is a "chat app", connections stay open and aren't closed quickly.

As you've seen, the ThreadPool starts off with a number of idle threads, and it will add threads as needed at a rate of approximately one every 500ms (although this is an implementation detail). This normally isn't a problem: you're not supposed to use the ThreadPool for very long-running tasks which never return, and which tie up threads forever. However, since your OnClientConnection method doesn't return for ages, you're just grabbing and hogging ThreadPool threads, and forcing the ThreadPool to keep expanding.

If you want to use a thread per client, you are probably best off creating a new long-running thread per client. However, this is pretty wasteful: you'll have loads of threads hanging around not doing very much. It's better to have a small number of threads which are constantly processing messages from a big pool of clients. It's possible to architect this yourself, but it's a lot easier to just use the async/await capabilities of TcpListener and NetworkStream.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!